python - sys.path什么时候修改?

标签 python python-2.7 sys

我在理解 official tutorial 中的这一段时遇到一些困难:

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

假设我有以下模块,名为 demo.py:

if __name__ == '__main__':
    import sys
    print sys.path

当前目录下还有一个名为sys.py的模块,只包含一个pass。我想使用这个模块来“隐藏”标准模块。

在终端,我执行并得到了

sunqingyaos-MacBook-Air:Documents sunqingyao$ python demo.py
['/Users/sunqingyao/Documents', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages']

所以我的问题是:sys.path 何时修改?

  • 如果在执行 import sys 之前对其进行了修改,则应导入 sys.py 而不是标准模块。
  • 如果在执行 print sys.path 后对其进行修改,'/Users/sunqingyao/Documents' 不应出现在 中>sys.path.

而且奇怪的是,修改发生在 import sysprint sys.path 的执行之间。

最佳答案

sys 是一个内置模块,它是解释器的一部分,不能被屏蔽,因为它在解释器启动时就已经加载了。

这是因为 sys.modules 是正在加载的模块的核心注册表,而 sys.modules['sys'] 指向其自身。任何import sys语句都会在需要搜索模块路径之前找到sys.modules['sys']

sys 不是唯一的内置模块,尽管它是唯一自动加载的模块。请参阅sys.builtin_module_names tuple用于编译到 Python 二进制文件中的其他模块。

这是 site module 的责任更新sys.path;它作为 Python 引导过程的一部分加载,除非您使用 -S command line switch .

关于python - sys.path什么时候修改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38411636/

相关文章:

python - OpenCV Python : Convert RGB to YCrCb

python - 在多列上使用 pandas groupby 函数

python - 无法连接 'str' 和 'int' 对象,但我可以通过我自己的 IDLE 正常运行它?

python - 从文件夹中选择前 n 个最小的文件

python-2.7 - 处理由 Python 代码产生的 C++ 子进程引起的段错误

python 2.7 : reload(sys) disables error messages and print in Windows

python - IPython sys.path 不同于 python sys.path

python - 通过另一列 pandas 找到列组的最大值

ubuntu - python 脚本到 .deb ubuntu 包来安装守护进程

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