I have a Python module that I call like this
python -m foo.bar arg1 -a foo --some-arg=10
And inside the bar.py
module, I need to query the command that was used to call the module. For example, get_raw_terminal_command()
would return "python -m foo.bar arg1 -a foo --some-arg=10"
.
I've seen several posts suggest import sys; sys.argv
but sys.argv
fails in multiple ways.
sys.argv
returns the full path thefoo/bar.py
file. I need the raw command for debugging purposes and callingpython /path/to/foo/bar.py
is not the same as callingpython foo.bar
- In my production use-case,
sys.argv
is returning['-c']
instead of the name or path of any Python module. I'm still in the middle of troubleshooting why this is happening but I've already made a case for whysys.argv
isn't what I'm looking for anyway.
Another popular solution is to use argparse
to rebuild the command-line input but I can't use it because I don't control how the Python code is being called. The solution must be generic.
Does anyone know how to get the raw command that is used to call a Python script from within the Python script? If possible, the solution should be compatible with Windows.