Skip to content

Mastering virtualenv

In this article we will see how to setting up a virtual environment and configuring a Jupyter kernel in order to manage project-specific dependencies and use them seamlessly in Jupyter notebooks 😎.

Step 1: Install Python

Ensure Python is installed on your system; you can download it from Python.org.

Step 2: Install virtualenv

Open your terminal or command prompt and run:

pip install virtualenv

You can also use the build in python command line for this like in the official documentation: python -m venv /path/to/new/virtual/environment

Step 3: Create a Virtual Environment

Navigate to the desired directory and create a virtual environment:

# Replace "myenv" with your preferred environment name
virtualenv env

This creates a folder, env, containing a dedicated Python environment.

Step 4: Activate the Virtual Environment

  • Windows:
    myenv\Scripts\activate
    
  • MacOS/Linux:
    source myenv/bin/activate
    

Step 5: Install Jupyter

Within your virtual environment, install Jupyter:

pip install jupyter

For macos users you can install it with homebrew like this : brew install jupyter

Step 6: Set up the jupyter kernel

A Jupyter kernel is a computational engine that executes the code you write in a Jupyter notebook. Essentially, it's the backend responsible for running the code in the notebook’s cells, processing it, and returning the results.

Each Jupyter notebook is associated with a specific kernel, which defines the language and environment used to interpret the code. Let's see how to install a new one.

pip install ipython ipykernel
python -m ipykernel install --user --name=myenv

Jupyter’s ability to support different languages through kernels makes it a versatile tool. You can even run different languages in the same notebook (using tools like %R or %%bash magic commands in the IPython kernel).

Let's continue this example by adding a Bash kernel with:

pip install bash_kernel
python -m bash_kernel.install

Step 7: Launch Jupyter Notebook

While still in the virtual environment, start Jupyter Notebook:

jupyter notebook

Step 8: Select Your Virtual Environment in Jupyter

In Jupyter web browser GUI follow this steps :

  1. Open or create a new notebook.
  2. Go to “Kernel” > “Change Kernel.”
  3. Select your virtual environment’s kernel (e.g., “myenv”).

To confirm Bash is working correctly, try:

%%bash
echo "Hello from Bash!"

Step 9: Deactivate the Virtual Environment

After finishing, deactivate with:

deactivate
You’ll need to reactivate the environment before using it again.