How does activating a python virtual environment modify sys.path?

The short answer is that activating a virtual environment does not change sys.path. sys.path is determined once Python starts up; see https://docs.python.org/3.7/library/sys.html#sys.path. What the virtual environment does, by adjusting your PATH environment variable, is change what interpreter actually runs when you simply run python.


sys.path is initiated in site.py, it is set using the relative path of sys.prefix, which is the path of python executable inside the virtual environment.

if the virtual environment is created without option --system-site-packages, which is the default, the config value of key include-system-site-packages set to false in pyvenv.cfg .

virtualenv has an identical option --system-site-packages, but it will write a file named no-global-site-packages.txt into the site dir of venv as a flag.

during python startup, site.py is executed, it will check pyvenv.cfg config file to set sys.path:

If “pyvenv.cfg” (a bootstrap configuration file) contains the key “include-system-site-packages” set to anything other than “true” (case-insensitive), the system-level prefixes will not be searched for site-packages; otherwise they will.

if venv is created with virtualenv, site.py in venv is a modified version, it check the existence of file no-global-site-packages.txt, if this flag file not exists, system-wide site package path will be added to sys.path, which is infered from sys.real_prefix.

update 2022: lastest virtualenv also use pyvenv.cfg.

hope this could answer your question.