[docs] [issue33119] python sys.argv argument parsing not clear

Jonathan Huot report at bugs.python.org
Thu Mar 22 05:21:13 EDT 2018


New submission from Jonathan Huot <jonathan.huot at thomsonreuters.com>:

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.

----------
assignee: docs at python
components: Documentation
messages: 314239
nosy: Jonathan Huot, docs at python
priority: normal
severity: normal
status: open
title: python sys.argv argument parsing not clear
type: behavior
versions: Python 2.7, Python 3.4, Python 3.5, Python 3.6, Python 3.7, Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue33119>
_______________________________________


More information about the docs mailing list