python script is looking to system environment even though virtual environment is activated

Question:

Running VS Code in Windows and Python 3.9x

I created a new project folder and created a new virtual environment for this project. The first script I created is a .ipynb file (jupyter notebook), and it works fine. When I exported the script to .py file, it generates an error on first line of code:

from pynput import keyboard

ModuleNotFoundError: No module named ‘pynput’

The pynput library is installed in this virtual env, which is why the .ipynb file runs fine. When I look at the lower right corner of VS Code, I can see the virtual env is activated:

enter image description here

And the terminal prompt is prepended with (proj_env). And when I run pip list, I can see the pynput package is installed. It is NOT installed in the system environment, which is why I’m guessing the script is trying to use system env, but I could be wrong.

What am I missing?

From the testing described in the comments, perhaps it has to do with a difference between how a Windows CMD window (running a vritual env) checks certain paths for packages the script wants to import vs how VS Code checks certain paths?

Asked By: jub

||

Answers:

Figured out the issue, which I didn’t quite understand when I asked the question, and a (the?) resolution. If anything in this answer is incorrect, please correct (and educate) me, thanks.

In VSCode, there is a difference between "Run Code" (this uses CodeRunner extension) and "Run Python File" (this runs file in terminal). The play button will use whichever of these was last run (open dropdown box next to play button).

I was having the same problem as this user: Run Code vs Run Python File in Terminal for VSCODE

The project’s settings.json file specifies the "python.defaultInterpreterPath" which points to the virtual environment’s python.exe. So when I run the .py file in terminal, the packages that are installed only in the virtual env (and not in the global/system environment) are found.

But Run Code uses Code-Runner, which is defaulting to the global environment’s python.exe and thus does not find the packages that are only in the virtual env. The solution is to specify which environment Code-Runner should use, by adding this to settings.json file:
"code-runner.executorMap": { "python": ""$pythonPath" $fullFileName", }
Since my settings.json file is already specifying the virtual environment’s python interpreter, this code snippet will tell Code-runner to use the same python interpreter to execute the code.

Answered By: jub
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.