Search code examples
pythonpython-3.xpython-venvpyvenv

Python virtual environment and `sys.path`


I created a virtual environment using

python -m venv venv

Now I'm opening a Python shell without activating the virtual environment by running

import sys
print(sys.path, sys.prefix)

I get

['', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/usr/lib/python3.12/site-packages'] /usr

which is exactly what I'm expecting.

While, if I activate the environment, the output is

['', '/usr/lib/python312.zip', '/usr/lib/python3.12', '/usr/lib/python3.12/lib-dynload', '/home/myname/mypath/venv/lib/python3.12/site-packages'] /home/myname/Projects/pypath/venv

What upset me a lot is that even inside the venv it seems that the interpreter is seraching packages firstly in the system-wide location, and only then inside the venv directory.

Is this true?


Solution

  • Is this true?

    No. The system packages are at /usr/lib/python3.12/site-packages, which is not present at all when you're "inside" the venv.

    The paths before the venv-site (which is /home/myname/mypath/venv/lib/python3.12/site-packages in your case) are for standard library imports.

    For example, if you import csv or some other stdlib module, then csv.__file__ will be found at /usr/lib/python3.12/csv.py.