Executing python modules with -m can lead to weird sys.argv parsing.
"Argument parsing" section at https://docs.python.org/3.8/tutorial/interpreter.html#argument-passing mention :
- When -m module is used, sys.argv[0] is set to the full name of the located module.
The word "located" is used, but it doesn't mention anything when the module is not *yet* "located".
For instance, let's see what is the sys.argv for each python files:
$ cat mainmodule/__init__.py
import sys; print("{}: {}".format(sys.argv, __file__))
$ cat mainmodule/submodule/__init__.py
import sys; print("{}: {}".format(sys.argv, __file__))
$ cat mainmodule/submodule/foobar.py
import sys; print("{}: {}".format(sys.argv, __file__))
Then we call "foobar" with -m:
$ python -m mainmodule.submodule.foobar -o -b
['-m', '-o', 'b']: (..)/mainmodule/__init__.py
['-m', '-o', 'b']: (..)/mainmodule/submodule/__init__.py
['(..)/mainmodule/submodule/foobar.py', '-o', 'b']: (..)/mainmodule/submodule/foobar.py
$
We notice that only "-m" is in sys.argv before we found "foobar". This can lead to a lot of troubles when we have meaningful processing in __init__.py which rely on sys.argv to initialize stuff.
IMHO, it either should be the sys.argv intact ['-m', 'mainmodule.submodule.foobar', '-o', '-b'] or empty ['', '-o', '-b'] or only the latest ['-o', '-b'], but it should not be ['-m', '-o', '-b'] which is very confusing.
|