I have a python script foo.py
in my current directory C:\test
.
Here is the code.
import sys
print('sys.path:', sys.path)
print('sys.argv:', sys.argv)
When I execute it as a script, I see this output.
C:\test>python foo.py
sys.path: ['C:\\test', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
sys.argv: ['foo.py']
But when I execute it as a module, I see this output.
C:\test>python -m foo
sys.path: ['', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
sys.argv: ['C:\\test\\foo.py']
Why does sys.path[0]
become empty string when I execute my program as a module?
The documentation at http://docs.python.org/3.4/library/sys.html#sys.path mentions this:
As initialized upon program startup, the first item of this list,
path[0], is the directory containing the script that was used to
invoke the Python interpreter. If the script directory is not
available (e.g. if the interpreter is invoked interactively or if the
script is read from standard input), path[0] is the empty string,
which directs Python to search modules in the current directory first.
So if the script directory is not available, only then it is supposed to set sys.path[0]
to ''
. But in my case, even while executing python -m foo
, the script directory foo
is clearly available. So it should not set sys.path[0]
to ''
as per the documentation. Instead, it should set it to 'C:\\test'
.
Is it a bug in the documentation or a bug in the Python interpreter or a bug in my understanding?