Sys.argv behavior with python -m

a question about __init__.py behavior in python 3.5.2. I noticed that "sys.argv" and "import __main__" behave differently depending on when they were called. For instance:

$ tree 
└── subdir
    ├── __init__.py : "import sys; print(sys.argv)"
    ├── __main__.py : "import sys; print(sys.argv)"

$ python -m subdir
['-m']
['/path/to/code/subdir/__main__.py']

Here I am taken by surprise, as I would expect sys.argv to be the same throughout the life of the processes. I have an intuition as to why this is happening, but I am wondering if there is a way to find out the import time that the true sys.argv is in the __init__.py module.

For reference, it looks like argv is changed in lib / runpy.py @ _run_module_as_main

+4
source share
1 answer

: __main__

:

  • -m sys.argv [0]
  • , sys.argv
    • main.c@Py_main
    • main.c@RunModule runpy.py@_run_module_as_main
    • _run_module_as_main sys.argv [0], , runpy.py@_get_main_module_details
      • _get_module_details , __init__.py script, _get_main_module_details , , _run_module_as_main sys.argv

, , sys.argv , _get_module_details ( , ), runpy, , this, .

+2

Source: https://habr.com/ru/post/1668970/


All Articles