Virtual Environment Inside Jupyter Notebook

10 Jan 2021

python

1. Introduction

In a previous post about Python virtual environment, I introduced to the virtual environment (venv) and how to create it. Today, I will show you how to set up venv inside your Jupyter notebook or Jupyter Lab. Make sure that you have read Python virtual environment before keeping on this post.

Contents

2. Installation

(.env) PS D:\demo> pip install jupyter
python -m ipykernel install --user --name=.envNameAny
Installed kernelspec .envNameAny in C:\Users\AnNg\AppData\Roaming\jupyter\kernels\.envnameany

Where --name is an argument for the name of venv in the kernel Jupyter. For the above example, .envNameAny is the name of venv in kernel Jupyter used for this demo (the name in ipykernel is not necessarily the same name as the venv is generated via python -m venv <envName>)

jupyter-notebook

3. The Results

To clarify the results, I installed numpy package before running jupyter-notebook. Fig 1 shows UI of the notebook when starting. You choose New > .envNameAny to create your notebook with venv.

UI when opening jupyter-notebook

Figure 1. UI when opening notebook


Let’s write our first magic code now.

first magic code

Figure 2. Final result