VS Code cannot find virtual environment on the interpreter, but can find it on integrated terminal

Viewed 534

I have a fully working virtual environment installed on my Linux machine. This venv can be regularly used by the terminal in VS code calling source /mypath/venv/bin/activate.

The problem is that the Python interpreter in VS code cannot access any of the packages in the virtual environment, despite setting up the path on the interpreter as described in most of the guides.

I decided to manually set up the path in the settings.json file inside the .vscode folder as follows:

{   
   "python.pythonPath": "/mypath/venv/bin/python3.8"
}

venv is still not accessible through the interpreter. Any other suggestions?

3 Answers

You actually do not need the settings.json file. I've have had a lot of problems lately too.

You could try to remove the .venv folder and create a new one by

python -m venv .env

It seems that vs code have changed something from .venv to .env. Im not sure why.

After doing python -m venv .env open the terminal in vs code and it will active your .env.

You could (if you froze your pip installations) do a pip install -r requirements.txt and you are all good to go.

The default for the "python.envFile" setting is "${workspaceFolder}/.env" change it to "${workspaceFolder}/.venv" and restart vscode.

I will answer my own question. Turned out my pip installation was pointing to a path (standard /home/username/.local/bin/pip) which was different from my venv directory (/my_path/venv/bin/pip). You can display the path by executing the command which pip.

In my very specific case, there was some mix-up when I first setup my Linux machine, meaning that venv only had a small amount of packages installed, while the directory containing the Python libraries and actually being used was the pip path. In other words, activating venv did not make any difference, since the Python libraries where loaded from the pip path.

So, first I had to ensure that pip had to point to the my venv folder, by modifying the .bashrc file in /home/username/, replacing

export PYTHONPATH=/home/username/.local/lib/python3.8
export PATH=/home/username/.local/bin:$PATH

with

export PYTHONPATH=/my_path/venv/lib/python3.8/
export PATH=/my_path/venv/bin:$PATH 

All I had to do after was re-installing each of the required packages in the newer venv (generating a requirements.txt file from the older pip path helped).

Then I selected the venv path in the VS Code interpreter and everything is working fine now.

Related