PYTHONPATH 如何填充 sys.path 是否可靠并记录在案?

Is it reliable and documented how PYTHONPATH populates the sys.path?

在我的机器上,来自 PYTHONPATH 的值似乎被插入到 sys.path:

例如,使用 PYTHONPATH=/spam:/eggs:/spam 然后签入 python -m site,我得到如下结果:

sys.path = [
    something,
    '/spam',
    '/eggs',
    more,
    stuff,
    after
]

在 Python 2 和 Python 3 上似乎是相同的行为。问题是,PYTHONPATH 的这种处理有多少被记录/可靠,如果在其他平台上可能有所不同吗?这是被嵌入到解释器中,还是由 site.py and/or 处理,有被系统管理员 "tweaked" 处理的危险?

我在文档 here 中看不到它的解释,它只是说 sys.path 是 "augmented"(而且,与文档相反,不存在的目录不会出现被默默地忽略)。

让我们往下看。


  • beginning at index 1

靠谱。如 PYTHONPATH docs

中所述

The default search path is installation dependent, but generally begins with prefix/lib/pythonversion (see PYTHONHOME above). It is always appended to PYTHONPATH.

An additional directory will be inserted in the search path in front of PYTHONPATH as described above under Interface options. The search path can be manipulated from within a Python program as the variable sys.path.

在PYTHONPATH 之前插入一个目录,可以是当前目录、脚本目录或其他目录,具体取决于您运行 Python。附加其他目录。 site module 也会向 sys.path 添加一些模块,但 site 也会附加:

Importing this module will append site-specific paths to the module search path and add a few builtins...


  • order preserved

我认为这在任何地方都没有明确记录,但搜索路径顺序很重要,更改它会破坏向后兼容性,我认为他们不会轻易做出。


  • de-duplicated

这是 site 模块的一个未记录的效果。如果您 运行 Python 带有禁用 site-S 标志,则不会发生这种情况。你可以在site.removeduppaths

中看到代码