Python 路径在哪里被操纵?

Where is Python path being manipulated?

在一台服务器上我可以导入库,在第二台服务器上我不能。我需要导入的库是通过 NFS 共享的,并且两台服务器都可以访问。

我发现 Python 路径在两个服务器之间不同,但是 Python 二进制文件是相同的,从标准 ubuntu 16.04 存储库安装,并且 $PYTHONPATH 在两台服务器上都未设置。

服务器 1:

$ echo $PYTHONPATH

$ python
>>> import sys; sys.path
['', '/usr/lib/python2.7', '...', '/usr/local/lib/python2.7/dist-packages', '/home/user/app/src/python', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/wx-3.0-gtk2']

服务器 2:

$ echo $PYTHONPATH

$ python
>>> import sys; sys.path
['', '/usr/lib/python2.7', '...', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

我如何理解这个库在哪里定义,以便将相同的行为复制到服务器 2?

奇怪的是,库位于路径 /usr/local/lib/usr/lib 之间。

编辑:python 二进制文件是相同的(相同版本 2.7.12,并且校验和匹配)并且它是从标准位置 /usr/bin/python 的 ubuntu 存储库安装的。
我玩过库 site 并且所有变量都是相同的(site.ENABLE_USER_SITE returns 正确)。
我知道我可以操纵脚本内的路径,或在 /etc/profile.d/ 中为所有服务器指定 PYTHONPATH,但我想知道区别在哪里。

Sys 模块文档说 sys.path

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default

参见:https://docs.python.org/3/library/sys.html

所以必须有不同的依赖于安装的默认设置。检查确切的 python 版本。也许 python 模块二进制文件来自不同的 apt 存储库。也许 python 命令来自两台服务器的不同位置 - 通过以下方式检查:

which python

同时检查 站点模块 - 它似乎控制了额外的路径。 参见:http://docs.python.org/3/library/site.html

我会导入它并检查 site.ENABLE_USER_SITE 也许它会给你一些关于不同之处的线索

我在 Python 中发现 路径配置文件 的存在。 来自 site module on Python 3:

的文档

It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.
...
A path configuration file is a file whose name has the form name.pth and exists in one of the four directories mentioned above; its contents are additional items (one per line) to be added to sys.path. Non-existing items are never added to sys.path, and no check is made that the item refers to a directory rather than a file. No item is added to sys.path more than once. Blank lines and lines beginning with # are skipped. Lines starting with import (followed by space or tab) are executed.

在我的例子中,/usr/local/lib/python2.7/dist-packages/easy-install.pth 中有一个文件在第二台服务器上丢失了。

使用 python -S 禁用这些文件的自动导入可能在调试时很有用。

不幸的是,我还没有找到一种方法来检索从中读取路径配置文件的目录列表。