How to Create a Virtual Environment in Jupyter Notebook? (For Windows, Mac & Linux)
Step 1: Create a Virtual Environment
In a Jupyter Notebook cell, you can create a virtual environment using the !
command, which allows you to run shell commands:
!python -m venv myenv
This will create a virtual environment named myenv
in the current working directory.
Step 2: Activate the Virtual Environment
Activating the virtual environment directly within a Jupyter Notebook isn't straightforward because the notebook's kernel is already running in a specific environment. However, you can manually install the packages within the venv
and then link the virtual environment to Jupyter Notebook as a new kernel.
Step 3: Install ipykernel
in the Virtual Environment
After creating the venv
, you can install ipykernel
into it. Run the following commands:
!myenv\Scripts\python -m pip install ipykernel # On Windows
# OR
!myenv/bin/python -m pip install ipykernel # On macOS/Linux
Step 4: Add the Virtual Environment to Jupyter Notebook
Now, you can add this virtual environment as a new Jupyter kernel:
!myenv\Scripts\python -m ipykernel install --user --name=myenv --display-name "Python (myenv)" # On Windows
# OR
!myenv/bin/python -m ipykernel install --user --name=myenv --display-name "Python (myenv)" # On macOS/Linux
--name=myenv
: This specifies the kernel's internal name.--display-name "Python (myenv)"
: This sets the display name in the Jupyter Notebook interface.
Step 5: Select the New Kernel in Jupyter Notebook
After running the above commands, go to the Kernel menu in your Jupyter Notebook.
Select Change kernel and choose "Python (myenv)" or whatever display name you set.
Now, your notebook will use the virtual environment you created.
Step 6: Install Packages Within the Virtual Environment
If you need to install additional packages in the virtual environment, you can do so by running:
!myenv\Scripts\pip install package_name # On Windows
# OR
!myenv/bin/pip install package_name # On macOS/Linux
Summary
Even though you can't directly "activate" a venv
within a notebook cell in the traditional sense, you can still create, configure, and use it by installing ipykernel
and adding it as a Jupyter kernel. This approach allows you to run your notebook with the specific environment configuration you need.
Subscribe to my newsletter
Read articles from Retr0 directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Retr0
Retr0
Hacker by night, coder by day - mastering the art of breaking and building (or at least making a heroic attempt)!