我认为 sys.path 是 Python 模块的所有搜索路径的完整列表。
但是,在我的 Ubuntu 机器上,“/usr/local/lib/python2.6/dist-packages/”几乎是我所有模块所在的位置,并且该路径不在 sys.path 中。而且我仍然可以在该路径上导入任何模块。
编辑,不正确:即使我将 sys.path 设置为空列表,我仍然可以从该路径导入。
dist-packages 路径的隐含知识从何而来?在这组隐式搜索路径中是否还有其他路径,或者它是什么?
编辑:我的帖子的第二部分似乎不是真的。事实上,“sys.path = []”意味着我不能导入任何东西,甚至不能从我当前的工作目录中导入。我很抱歉。
最佳答案
注意 following 中提到的依赖于安装的默认值。 :
6.1.2. The Module Search Path
When a module named
spam
is imported, the interpreter searches for a file namedspam.py
in the directory containing the input script and then in the list of directories specified by the environment variablePYTHONPATH
. This has the same syntax as the shell variablePATH
, that is, a list of directory names. WhenPYTHONPATH
is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually.:/usr/local/lib/python
.Actually, modules are searched in the list of directories given by the variable
sys.path
which is initialized from the directory containing the input script (or the current directory),PYTHONPATH
and the installation-dependent default. This allows Python programs that know what they’re doing to modify or replace the module search path. Note that because the directory containing the script being run is on the search path, it is important that the script not have the same name as a standard module, or Python will attempt to load the script as a module when that module is imported. This will generally be an error. See section Standard Modules for more information.
编辑 在我的 Ubuntu 机器上,
/usr/local/lib/python2.6/dist-packages
存在于 sys.path
.如果我清除 sys.path
然后尝试从上述目录导入一个模块,该模块不再有效。这表明解释器对该目录没有隐含的知识,而是通过 sys.path
找到它。 .编辑 进行实验时,请务必修改
sys.path
在 Python session 开始时。如果您 import X
,然后清除 sys.path
,然后是 import X
同样,即使 X
后者也不会失败不再在 sys.path
上.
关于python - 搜索路径是否比 sys.path 中的多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6697525/