Adding custom kernels to a Jupyter notebook in Visual Studio
Jupyter notebooks are some of the most widely used tools for data science. Combined with Visual Studio, it can be the ideal tool for efficient coding and analysis. Each project might have different dependency requirements and virtual environments are python’s solution to package management across different projects.
However, with each virtual environment we would need to add it to the jupyter notebook kernels for utilizing the python version in this virtual environment and also the installed packages.
In this article, we shall go step by step how to add different virtual environments to the set of jupyter kernels available and also how to configure the required kernel in visual studio so that we can run this notebook with the particular kernel. For this article you would need to have installed Visual Studio with Jupyter notebook extension.
1. Create a new notebook in visual studio code
First, create an ipython notebook say test_file.ipynb, and add a few lines. In this article we have a simple import statement.
2. Create the required virtual environments
Next let’s create the required virtual environments, venv1 and venv2 and install different version of the numpy package in them.
3. Add the virtual environments to the available Jupyter kernels
In order to add these kernels to the set of available jupyter kernels, we would need to setup the ipykernel package within them.
a. Firstly activate the environment.
<path_to_venv1>\venv1\Scripts\activate
b. Install the ipykernel package.
pip install ipykernel
c. Add the environment to the kernels.
Please do have a look at this informative answer for reference.
4. Configure Visual Studio to use the particular kernel
After the environments are added to the kernels, make sure to restart Visual Studio for the current project. This step is mandatory for it to be able to detect the new kernels.
Click on “Select Kernel “ to choose the required kernel and we shall be able to see the newly added kernels.
And, that’s it ! You can now run the Jupyter notebook with different kernels as per your choice and hence use different package versions.