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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With