sys.argv behavior with python -m
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping
--
Chapters
00:00 Question
01:04 Accepted answer (Score 3)
02:43 Thank you
--
Full question
https://stackoverflow.com/questions/4207...
Accepted answer links:
[module specs]: https://www.python.org/dev/peps/pep-0451/
[this]: http://bugs.python.org/issue26388
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #pythonimport
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping
--
Chapters
00:00 Question
01:04 Accepted answer (Score 3)
02:43 Thank you
--
Full question
https://stackoverflow.com/questions/4207...
Accepted answer links:
[module specs]: https://www.python.org/dev/peps/pep-0451/
[this]: http://bugs.python.org/issue26388
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #pythonimport
#avk47
ACCEPTED ANSWER
Score 5
Short Version: there is no way to find __main__ before it is run
Long Version:
- the -m flag causes sys.argv[0] to be manipulated
- the problem is in the timing with which sys.argv is manipulated
- main.c@Py_main does some flag parsing and pops off the module name to call
- main.c@RunModule a wrapper around runpy.py@_run_module_as_main
- _run_module_as_main sets the sys.argv[0] but does not do so until after calling runpy.py@_get_main_module_details
- a side effect in _get_module_details actually imports the package and its ancestors which executes the __init__.py script before _get_main_module_details can resolve thus _run_module_as_main can't set sys.argv
I think this could be refactored such that sys.argv is set before _get_module_details imports the package and ancestors (I think made possible by module specs) but will have to wait for an enhancement to the runpy architecture, possibly in the form of this which was in the works as of late last year.