Search code examples
pythonjupyter-notebookvirtualenvjupytervirtual-environment

multiple commands in a notebook cell to activate virtual env


I am using Jupyter Notebook and the present working directory is home/abcde.

However, I want the virtual environment use python 3 interpreter and directory be created under the below path

!mkdir python-virtual-environments && cd python-virtual-environments && virtualenv env && virtualenv -p python3 env && .python-virtual-environments/env/bin/activate

Here, instead of the source keyword, I have to use . based on this post

However, I am getting the below error.

 re/virtualenv/seed-app-data/v1.0.1)
 activators PythonActivator,FishActivator,XonshActivator,CShellActivator,PowerShellActivator,BashActivator
/bin/sh: 1: .python-virtual-environments/env/bin/activate: not found   #error is here in this line.

Can you help on how can I execute this command?

If I break down the commands and put them in each cell, the folders are being created in the pwd which is home/abcde


Solution

  • The error is because you're already in the env directory, and then you're executing .python-virtual-environments/env/bin/activate.

    You need to run . env/bin/activate as follows:

    !mkdir python-virtual-environments && cd python-virtual-environments && virtualenv env && virtualenv -p python3 env && . env/bin/activate
    

    If I break down the commands and put them in each cell, the folders are being created in the pwd which is home/abcde

    It's because each terminal command (using !) is executed in a new shell. So, cd python-virtual-environments becomes useless, you can instead use %cd python-virtual-environments/ if you want to run each command independently or use %%bash.

    %%bash
    
    mkdir python-virtual-environments
    cd python-virtual-environments
    virtualenv -p python3 env
    . env/bin/activate