How to Run a Jupyter Notebook in a Virtual Environment

To help make our interactive data analysis that's in a Jupyter Notebook reproducible, I'd like to encourage you to run it in virtual environments. This helps you keep track of what packages -- and what versions -- were used for a given project. Here are the 4 steps to doing so. 

Step 0: Decide on a Name for the Virtual Environment

Suppose we want to name our virtual environment env-project-a.

Step 1: Create the Virtual Environment

Approach a: Create a virtual environment via the Anaconda distribution of Python

Terminal, do all of the following:

conda create --name env-project-a

conda activate env-project-a

conda deactivate

Approach b: Create a virtual environment via the official Python distribution

Terminal, do all of the following:

export VIRTUALENVWRAPPER_PYTHON=$(which python3.7)

source /usr/local/bin/virtualenvwrapper.sh

export WORKON_HOME=./Envs

mkvirtualenv env-project-a

source ./Envs/env-project-a/bin/activate

deactivate

Step 2: Use Virtual Environment with your Notebook

ipython kernel install --user --name=env-project-a

jupyter lab

Step 3: Updating the Virtual Environment in a Notebook

If you need to change the name of the virtual environment previously associated with a Jupyter Notebook, you'll need to edit the notebook's metadata. 

Approach a: Using your favorite text editor

Approach b: Directly in the notebook

Tips

pip install -r requirements.txt

Keywords: Data products, reproducibility, virtual environments, python, Jupyter Lab, Jupyter notebook, Anaconda, conda, pip, notebook metadata

You may also like: