简体   繁体   中英

Value of sys.path differs between windows and linux when setting up a virtual environment

When creating a virtual environment via python -m venv.venv and then activating this environment I notice that on Windows the root directory of the environment is part of the import path as reported by sys.path but for linux it's not.

Python version: 3.8.2

Example:

python -m venv .venv

On Windows:

>>> import sys
>>> sys.path
['', 'c:\\temp\\.venv\\Scripts\\python36.zip', 'C:\\Python36\\DLLs', 'C:\\Python36\\lib', 'C:\\Python36', 'c:\\temp\\.venv', 'c:\\temp\\.venv\\lib\\site-packages']
>>> sys.prefix
'c:\\temp\\.venv'

Notice the entry c:\\temp\\.venv in the path.

On Linux:

>>> import sys
>>> sys.path
['', '/usr/local/lib/python38.zip', '/usr/local/lib/python3.8', '/usr/local/lib/python3.8/lib-dynload', '/carsten/.venv/lib/python3.8/site-packages']
>>> sys.prefix
'/carsten/.venv'

Notice that the root of the environment is NOT part of the path.

Is this difference by design or is this a bug?

The Windows case also has the installed prefix directory "C:\Python36", which is added by the interpreter startup code, in addition to the venv prefix directory that's added by site.py. Adding these directories is a vestige from long ago. There's no compelling reason that either "C:\Python36" or "C:\temp\.venv" needs to be in sys.path . Though someone somewhere is probably depending on it.

Adding the prefix directory used to be productive in early versions of the Windows release back in the 1990s, which initially put standard-library extension modules in the prefix directory instead of a dedicated "DLLs" subdirectory, plus it also used the prefix directory for site packages. For example, see site.py from 1997-08-09. A few iterations later , "site-packages" was added in Unix, but Windows was still using the prefix directory.

Finally, a few years later on 2001-07-12 , "site-packages" was added to the Windows release of Python 2.2, but in addition to the prefix directory instead of replacing it in sys.path . This was proposed by Paul Moore (still an active core developer) in PEP 250 , who notes that the prefix directory is being retained in order to support.pth files added there.

In the current implementation of site.py, addsitepackages calls getsitepackages , for which if the path separator is backslash (a weird way to identify Windows given the better ways available), it first adds prefix and then os.path.join(prefix, libdir, "site-packages") .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM