Author Jonathan Huot
Recipients Jonathan Huot, docs@python
Date 2018-03-22.09:21:12
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1521710473.18.0.467229070634.issue33119@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2018-03-22 09:21:13Jonathan Huotsetrecipients: + Jonathan Huot, docs@python
2018-03-22 09:21:13Jonathan Huotsetmessageid: <1521710473.18.0.467229070634.issue33119@psf.upfronthosting.co.za>
2018-03-22 09:21:13Jonathan Huotlinkissue33119 messages
2018-03-22 09:21:12Jonathan Huotcreate