The Python Oracle

sys.argv behavior with python -m

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle3

--

Chapters
00:00 Sys.Argv Behavior With Python -M
00:51 Accepted Answer Score 5
02:07 Thank you

--

Full question
https://stackoverflow.com/questions/4207...

--

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.