Question

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?

No correct solution

OTHER TIPS

Look at what man python says about -m:

-m module-name

Searches sys.path for the named module and runs the corresponding .py file as a script.

If you think about it, it makes no sense to add the directory containing the .py file to be run into sys.path, as it already has to be there to be found in the first place. So, IMO, the behavior is correct.

But the documentation says that if it is run as a script, the directory containing it should be prepended to sys.path. I would say that it is an error in the documentation, it should say:

[...] (e.g. if the interpreter is invoked interactively or if the script is read from standard input or if the script is run using the -m option) [...]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top