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:
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:
This creates a folder, env
, containing a dedicated Python environment.
Step 4: Activate the Virtual Environment
- Windows:
- MacOS/Linux:
Step 5: Install Jupyter
Within your virtual environment, 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.
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:
Step 7: Launch Jupyter Notebook
While still in the virtual environment, start Jupyter Notebook:
Step 8: Select Your Virtual Environment in Jupyter
In Jupyter web browser GUI follow this steps :
- Open or create a new notebook.
- Go to “Kernel” > “Change Kernel.”
- Select your virtual environment’s kernel (e.g., “myenv”).
To confirm Bash is working correctly, try:
Step 9: Deactivate the Virtual Environment
After finishing, deactivate with:
You’ll need to reactivate the environment before using it again.