2016-07-16 85 views
1

我遇到一些困難,瞭解本款在official tutorial何時修改sys.path?

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之間發生的修改也很奇怪。

+1

你在你的問題中混淆了'sys.argv'和'sys.path'。你在說哪一個? –

+2

'sys'是*內置*模塊,不能被屏蔽。 –

回答

2

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

+0

可以注意到,如果沒有'sys'已經被加載,爲了訪問'sys.path',導入機制甚至不知道在哪裏尋找外部'sys'模塊。 –

+0

但是如果'sys'是自動加載的,爲什麼我們需要編寫'import sys'? –

+3

@sunqingyao:'import'確實有兩件**事情:如果尚未加載模塊,則加載模塊(插入到'sys.modules'中),*綁定當前模塊中的名稱*。 –