Jupyter notebooks in Visual Studio Code does not use the active virtual environment - visual-studio-code

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?

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

All you need is to edit Vscode settings following these steps:
Open Open User settings using shortcut Ctrl + Shift + P
Type in search space "env"
Under Extentions -> Python , you will find Python: Venv Path
Type the absolute path to your enviroment "path/to/myenv/bin" in linux or "path/to/myenv/Script/"
Restart vsCode
Select the desired kernel using Notebook : Select Notebook kernel using shortcut Ctrl + Shift + P
Read more here: https://techinscribed.com/python-virtual-environment-in-vscode/

For VSCode, your Jupyter kernel is not necessarily using the same python interpreter you're using at the command line.
Use Ctrl + Shift + P to open the Command Palette, and select "Notebook: Select Notebook Kernel"
Then choose the interpreter you're using at the terminal

I find it easy to use pipenv install ipykernel to set up the virtual environment with the Jupyter kernel in one go (comment on rocksteady's answer).

Encounter the same behaviour. Python code works perfectly fine, but Jupyter refuses to pick up the local .venv.
The local venv is in Python: Select Interpreter but not in Jupyter's Select kernel list.
The problem is there're too many venv in the system!
If you encounter the same behaviour,
Press F1, then Jupyter: Filter kernels, uncheck everything, except the local env.
Then F1 -> Developer: Reload Window.
Jupyter will automatically use the default local venv.

for me solved by adding the path of my venv to the settings.json,
now the kernel is detected automatically
"python.pythonPath": "P:\Miniconda3_64bit\venv\Scripts\python.exe",

Make sure you have installed jupyter, notebook, ipykernel libraries in your virtual environment.
Then hit Ctrl + Shift +P , press >Python: Select Interpreter and choose your path of the venv.
After that, hit Ctrl + Shift +P again, run >Notebook: Select Notebook kernel.
If you have already opened the jupyter notebook window , reload it again and you can find your path of the venv in Jupyter's Select kernel list.

On macOS I have .venv/ in the same folder as my .ipynb
. .venv/bin/activate
pip install ipykernel
Then I restart VSCode in the project folder, open the notebook, and in the Select Kernel dropdown I see .venv/bin/python
Selecting that, now it works.

Here is how to do for venv with Jupyter Notebook on VSCode in Windows:
Create a venv and get the path to this venv in Windows. As an example, with Anaconda, I get: C:\Users\rascoussier\Anaconda3\envs\research310.
Now, we need to tell VSCode to use it. In VSCode, go to the Python Extension > Extension Settings. Search for Python: Venv Path. Add the path where the venvs are located. Here we added C:\Users\rascoussier\Anaconda3\envs\research310.
Restart VSCode.
Now launch command pallet(ctrl+shift+P) and run >Notebook: Select Notebook kernel. Normally the venv python should be available and it should then works.

Try a few things:
Make sure you can run the code from a Visual Studio Code terminal using the "ipython" prompt with the same Conda environment.
If it works then sometimes it is a caching issue, so close your file and open a new one.

Now let me show you a scenario. You select the interpreter in Visual Studio Code, and then you write codes below '# %%'. The moment you hit Ctrl + Enter, you are guessing that the IPython kernel that Visual Studio Code is using is not of the interpreters that you have selected. In this case you could write the following code to conform which interpreter is used for IPython kernel.
import sys
print(sys.executable)
This shows the executable path that the IPython kernel is using. If you see that it's not taking the correct interpreter then here's something that worked for me.
Just restart your computer. Then reopen Visual Studio Code and reselect the interpreter and again hit Ctrl + Enter. Now this time Visual Studio Code should take the correct interpreter and its IPython kernel.
See the final output image

If this happens while using WSL server, don't forget to install Python in the WSL as well, because it doesn't come automatically from the local installation to the server.
https://code.visualstudio.com/docs/remote/wsl-tutorial

Another alternative is to specify the folders where the environmental variables should be sought for.
Create your virtual environment using conda create --name ENV_NAME e.g conda create --name pwd
Then, conda activate pwd
It Should print out details like this:
Use that environment location
Edit Vscode settings following these steps:
Open Open User settings using shortcut Ctrl + Shift + P
Type in search space "env"
Under Extentions -> Python , you will find Python: Venv Folders
(See the image below)

Try installing the Anaconda Extension pack.
When I code in Visual Studio Code with this extension in the bottom left corner, I can select the virtual environment I want to execute my code in. Hence installing this package should make the trick.

Related

How to activate the current venv (not by conda/venv) in terminal VSCode

I'm using the virtual environment created from Pycharm as interpreter for my jupyter notebook project in VSCode. The venv hasn't been created by either conda or virtualenv so I cannot activate the venv in VSCode terminal as usual such as conda activate venv_name or . /Scripts/activate.bat...
Could anyone give a hand on how to activate the current venv/interpreter in terminal VSCode? Thank you.
You can find where that PyCharm environment is located -- use the Run > Edit Configurations menu, and look in the Python interpreter box:
There should be some script, such as activate in that location.

Intellisense autocomplete not working for wsl in vscode

I've been setting up vscode as an IDE for python development. I use windows subsystem for linux with my python packages installed through anaconda there.
My problem is that auto completion does not work as expected. For examples, outside of wsl if I am using the numpy package I can get autocompletion:
Autocomplete outside of wsl
However, inside of wsl autocomplete does not find numpy.linalg (as in example above):
Autocomplete inside wsl
Thanks in advance!
edit: I am currently using wsl1 if that information is relavent!
As mentioned by #Adriana Hernández you need to install the extensions inside WSL too.
The VSCode WSL docs are covering these here
In short if you go to the extensions tab, you shall see Python marked with "Install in WSL...". Once clicked install and reloaded, it should work.
If not you likely need to pick another interpreter (likely the one from your venv.)
hit Ctrl+Shift+P then
Python: Select interpreter
then select the desired python interpreter (most likely the one in your venv which has all the packages)
What works for me is creating a venv, activating then launching VSCode from WSL with code .
On the first time you will need to install your extensions to WSL, but then it should be good to go.

Setting up jupyter kernel in remote VSCode notebook

I am trying to run some notebooks in my virtual environment in the VSCode (remotely connected). I install the venv as usual via python3 -m venv <venv-name>, activate it and install all the needed modules. When I run which ipython I get the one from the venv so I install the kernel via ipython kernel install --name "<name>" --user and it is successfully created in ~/.local/share/jupyter/kernels/ directory and the kernel.json points to the venv python. Then I open the VSCode and select both the Python: Select Interpreter and Jupyter: Select Interpreter to start Jupyter server to point to the virtual environment's python, sth. like .../<venv-name>/bin/python3.
However, when I try to run the cell it wants me to select kernel (I can also do it myself in the upper right corner of the VSCode), but my newly created kernel is not there. There are only two (same) ones from usr/bin/python.
It is really strange since twice in two days my kernel magically appeared for one notebook and worked as desired, but when I opened a new notebook, my kernel was gone again. I tried to remove/reinstall kernels, venvs, VSCode's Python and Jupyter extensions but nothing helped. Any suggestions?
For now, I start the kernel in remote command-line via jupyter notebook --no-browser --ip=<ip> and then insert the connection link to Jupyter Server in the bottom right corner of the VSCode status bar but am wondering if there is an easier way since all the stuff (except VSCode) is on a remote machine?
This way is not easy. You can set up Jupyter Kernel easily.
Firstly, using ssh to connect to the remote server.
Secondly, open Command Palette (⇧⌘P) and enter Python: Select Interpreter, you can directly connecting to remote kernel.
resource: https://code.visualstudio.com/docs/datascience/jupyter-notebooks

Wrong Python interpreter being used by VS Code

I am on Ubuntu 20.04 and have both Python2 and Python3 installed natively. I have also installed Python through miniforge, a variant of miniconda. In VSCode I have both the MS Python extension and Pylance installed.
I use the miniforge python for my coding. This works perfectly fine in PyCharm.
However in VSCode, when I try to execute the same file I get errors. After investigating it seems that VSCode is picking native Python2 - even though I have the miniforge Python selected. In this picture it can be seen that the status bar at the bottom states Python interpreter selected is Python3. But the output window shows that the python interpreter is Python2.
A more confusing thing is when I use VSCode for Jupyter notebook files then it picks up the interpreter correctly and I have no issues.
I have checked both User and Workspace settings, and they all point to Python3. How can I fix this for standard .py files?
I prefer VSCode to PyCharm, but will need to use PyCharm till this is resolved.
It seems that your system console cannot see python3. You need to put the python3 in the PATH variable, before python2. Like:
PATH=path/to/python3:path/to/python2:$PATH
Also, make sure that the environment containing python3 is activated before command prompt appears. It can be done in bash_profile by adding a line like
conda activate my_env_with_python3
Try changing the settings "Python:Python path", "Python:default interpreter path" and "Python:conda path" also.
I have just bumped into something similar. The Run code option resulted in the file being run with the default interpreter instead of the venv-based one with necessary packages installed.
The fix was simply to use "Run python file" instead:
The run-code behavior must be customizable, something is mentioned e.g. here: Run Code vs Run Python File in Terminal for VSCODE but I didn't bother.

"Running cells requires Jupyter notebooks to be installed" error in VS Code

I'm trying to use the new Jupyter integration for the Python extension in VS Code, and I'm getting the above error even though I have Jupyter installed and it works fine from the command prompt.
Here's my environment:
Python extension version 2018.10.1, and I see Run Cell/Run All Cells tooltips above #%% comments.
I've used the Python: Select Interpreter command to select my Anaconda environment, which is at ~/AppData/Local/Continuum/anaconda3/python.exe.
I have Jupyter installed in that interpreter (jupyter.exe is in the Scripts sub-folder under that location), and it runs fine with the jupyter notebook command at the Anaconda prompt.
But whenever I click on Run Cell or press shift-enter, I get this error message:
"Running cells requires Jupyter notebooks to be installed." Source: Python (Extension)
Is there something else I need to do to configure this?
You may give one try by restarting VS Code in following mentioned way [ It worked for me. ]
Open Bash or any other cmd
Activate any conda environment [ See below command ]
source activate base [ means activate base environment ]
Run VS Code instance [ See below command ]
code .
Now when you'll click on Run Cell or press shift-enter, it should work.
The problem is an issue in the VS Code python extension itself. There are a number of issues related to this open in the repository: #3354, #3343, #3330, and the issues are being worked on, see #3374.
The reason, as far as I understand, is that in this case - and in some other cases - the anaconda environment is not activated before running the command. Situations where the environment is activated are e.g. opening a python terminal or running a file in the python terminal, but this also needs to happen for Jupyter, Tests, and so on.
While theoretically, adding the Scripts folder to your PATH, as David mentioned, could help, it did not help in my case. This may just not be enough to properly reflect what happens on activation.
My guess is that we will have to wait for this issue to be resolved in the repo, but if someone else finds a workaround, I'd be happy.
Simply running vscode from the activated environment did not work for me, here is what did:
In terminal (bash) I ran:
conda activate <environment-name>
conda install jupyter notebook
When the install finishes, open vscode from terminal (the same shell with activated environment) with the command:
code .
Notes:
Replace '.' with the path to the directory you want to open if it's not the current directory.
I've written 'conda install ...' but mamba also works.
If the terminal command for 'code ' does not work, it's likely you need to add it to environemnt variables; in such a case, this post might help.