Reputation: 16097
I'm having some difficulty understanding this paragraph in the 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.
Say, I have the following module, named demo.py
:
if __name__ == '__main__':
import sys
print sys.path
There is another module named sys.py
under the current directory, containing only a pass
. I want to use this module to "shadow" the standard modules.
At the terminal, I executed and got
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']
So my question is: When is sys.path
modified?
import sys
is executed, sys.py
should be imported instead of the standard module.print sys.path
is executed, '/Users/sunqingyao/Documents'
shouldn't occur in sys.path
.And it's also weird that the modification happened between the execution of import sys
and print sys.path
.
Upvotes: 1
Views: 288
Reputation: 1121186
sys
is a built-in module, it is part of the interpreter, and cannot be masked because it is already loaded when the interpreter starts.
That's because sys.modules
is the core registry for modules being loaded, and sys.modules['sys']
points to itself. Any import sys
statement will find sys.modules['sys']
before the module path needs to be searched.
sys
is not the only built-in module, although it is the only one that is auto-loaded. See the the sys.builtin_module_names
tuple for the other modules that are compiled into your Python binary.
It is the responsibility of the site
module to update sys.path
; it is loaded as part of the Python bootstrap process, unless you used the -S
command line switch.
Upvotes: 2