'How to make launcher in VS Code use my virtual environment?

Here is a little python script that demonstrates the problem.

import platform
print(platform.python_version())
print('okay')
from PIL import Image, ImageDraw

When I run it from the terminal within VS Code, it works as expected:

(.default) saul@linuxBox:~/Projects/PythonProjects/medSched$ python test.py
3.10.4
okay

When I run it with the launcher (Run..Run Without Debugging) it fails:

(.default) saul@linuxBox:~/Projects/PythonProjects/medSched$  cd /home/saul/Projects/PythonProjects/medSched ; /usr/bin/env /bin/python3.10 /home/saul/.vscode/extensions/ms-python.python-2022.4.1/pythonFiles/lib/python/debugpy/launcher 39803 -- /home/saul/Projects/PythonProjects/medSched/test.py 
3.10.4
okay
Traceback (most recent call last):
  File "/home/saul/Projects/PythonProjects/medSched/test.py", line 4, in <module>
    from PIL import Image, ImageDraw
  File "/usr/lib/python3/dist-packages/PIL/Image.py", line 69, in <module>
    from . import _imaging as core
ImportError: cannot import name '_imaging' from 'PIL' (/usr/lib/python3/dist-packages/PIL/__init__.py)

The terminal knows to use my virtual environment, but the launcher apparently does not, because if I run python3.10 test.py in the global environment, I get the same error. Can you tell what have I done wrong? How do I fix it?



Solution 1:[1]

I found a fix. In the command menu, I went to Python: Select Interpreter and entered the path to the interpreter in my virtual environment, /home/saul/.virtualenvs/.default/bin/python That works now, but I don't know if I've set it for this project or all projects. There must be a better way of doing this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 saulspatz