python - 搜索路径是否比 sys.path 中的多?

标签 python sys.path module-search-path

我认为 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 named spam.py in the directory containing the input script and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH 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/

相关文章:

lua - 如何设置搜索路径允许lua插件作为包

python - 由 numpy.linalg.eig 创建的特征向量似乎不正确

python - 由于单引号和双引号,正则表达式不工作

python - 在python中将日期转换为json日期字符串

python - 为什么 random.random() 在 Python 中不安全?

python - Sys.path.insert 插入模块路径,但导入不起作用

python - 特定于应用程序的 PYTHONPATH

python - 如何在 MacOS X 上添加 python 模块?