Reputation: 998
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 the foo/bar.py
file. I need the raw command for debugging purposes and calling python /path/to/foo/bar.py
is not the same as calling python foo.bar
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 why sys.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.
Upvotes: 0
Views: 352
Reputation: 26
This won't be compatible with windows, but in GNU/Linux or Solaris (credit: tripleee) you should be able to use /proc/self/cmdline to see exactly how you were called :
Import os
with open("/proc/self/cmdline") as f:
print(f.readline())
Upvotes: 1
Reputation: 998
I found something that may be helpful for Windows users: https://bytes.com/topic/python/answers/706727-get-complete-command-line
I'll paste the code again, here:
import ctypes
p = ctypes.windll.kernel32.GetCommandLineA()
print ctypes.c_char_p(p).value
The ctypes
solution worked for me. Another commenter pointed out that pywin32 also has its own flavor:
import win32api
print win32api.GetCommandLine ()
I didn't test it but that may work better.
Upvotes: 0