Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jupyter notebooks in Visual Studio Code does not use the active virtual environment

I write Python code in Visual Studio Code and run the program from a terminal in which I have activated a virtual environment, and it works fine.

However, if I create notebook cells using #%% and run those interactively, the virtual environment is not used. How can I fix this?

like image 782
Henrik Leijon Avatar asked Sep 26 '19 15:09

Henrik Leijon


People also ask

Is Jupyter Notebook a virtual environment?

Open the directory where you want to create your project. open cmd/powershell and navigate to the same directory and run the following commands to create a virtual environment. Now as we have our virtual environment let's activate it.

What environment does Jupyter Notebook use?

Activate a conda environment in your terminal using source activate <environment name> before you run jupyter notebook . This sets the default environment for Jupyter Notebooks. Otherwise, the [Root] environment is the default.


1 Answers

It's because there is an extra step needed - you need to explicitly install a Jupyter kernel that points to your new Python virtual environment. You can't simply activate Jupyter-lab or Notebook from the virtual environment. This has tripped me up before, too.

Follow the advice here: Using Jupyter notebooks with a virtual environment

And, in fact, there can be an issue where your kernel still doesn't point to the correct Python binary, in which case you need to change one suggestion in the above advice process:

From: ipython kernel install --user --name=projectname

To: python3 -m ipykernel install --user --name=projectname

(This correction comes from a comment to Jupyter Notebook is loading incorrect Python kernel #2563.)

*and don't forget to restart VSCode

like image 86
rocksteady Avatar answered Oct 10 '22 00:10

rocksteady