Config virtual environment python on Jupyter Lab

Pham Ngoc Quy
2 min readMay 12, 2020

--

Are you working with Jupyter Lab and Python? Do you have occurs when Jupyter lab using root python environments
In this tutorial, I will guide you on how to config specify python virtual environments for the Jupyter lab.

Create Virtual Environment with Virtualenv/venv

A commonly used tool for virtual environments in Python is virtualenv. Since Python 3.3, a subset of virtualenv has been integrated into the Python standard library under the venv module. If you are using Python 2, you can install virtualenv with:

pip install --user virtualenv

Now, you can create a virtual environment with:

python3 -m venv IVenv

Add Virtual Environment to Jupyter Lab

Jupyter Lab makes sure that the IPython kernel is available and it use root python environments, but you have to manually add a kernel with a different version of Python or a virtual environment. First, you need to activate your virtual environment. Next, install ipykernel which provides the IPython kernel for Jupyter:

pip install --user ipykernel

Next, you can add your virtual environment to Jupyter by typing:

python -m ipykernel install --user --name=IVenv

This should print the following:

Installed kernelspec IVenv in /home/{user}/.local/share/jupyter/kernels/ivenv

In this folder, you will find a kernel.json file which should look the following way if you did everything correctly:

{
"argv": [
"/home/{user}/IVenv/bin//python3",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"display_name": "IVenv",
"language": "python"
}

Now, you can choose what python environment you want to run Jupyter Lab:

Change kernel
Choose python env

Hope my tutorial helpful to you.

--

--