Cannot import modules in Python venv

2.8k Views Asked by At

I'm running python3 in a virtual environment, but when I try to import newly install packages, I get a ImportError: No module named ... error message, despite seeing that package when I run !env/bin/pip3 list.

When I type sys.path I don't see any paths to my virtualenv:

['',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
'/Users/zurfarosa/Library/Python/3.5/lib/python/site-packages',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/IPython/extensions',
'/Users/zurfarosa/.ipython',
'/Users/zurfarosa']

How do I add my virtual env to my PYTHONPATH?

1

There are 1 best solutions below

0
On

In my case I had to change interpreter, because default was global, not the one in virtual env.

Output printing paths in sys.paths (where import is looking):

c:\Coding\py scripts\test_interpreter_location
C:\Users\[NAME]\AppData\Local\Programs\Python\Python37-32\python37.zip
C:\Users\[NAME]\AppData\Local\Programs\Python\Python37-32\DLLs
C:\Users\[NAME]\AppData\Local\Programs\Python\Python37-32\lib
C:\Users\[NAME]\AppData\Local\Programs\Python\Python37-32
C:\Users\[NAME]\AppData\Roaming\Python\Python37\site-packages
C:\Users\[NAME]\AppData\Local\Programs\Python\Python37-32\lib\site-packages
C:\Users\[NAME]\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32
C:\Users\[NAME]\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32\lib
C:\Users\[NAME]\AppData\Local\Programs\Python\Python37-32\lib\site-packages\Pythonwin

Having changed IDE interpreter to Python.exe inside virtual environment directory, now gives:

c:\Coding\py scripts\test_interpreter_location
c:\users\[NAME]\appdata\local\programs\python\python37-32\python37.zip
c:\users\[NAME]\appdata\local\programs\python\python37-32\DLLs
c:\users\[NAME]\appdata\local\programs\python\python37-32\lib
c:\users\[NAME]\appdata\local\programs\python\python37-32
C:\Coding\py scripts\test_interpreter_location\env
C:\Coding\py scripts\test_interpreter_location\env\lib\site-packages # <- where your env installed packages are

To change interpreter in VSCode click at the bottom right (env interpreter active in screenshot): enter image description here