python argparse how to get entire command as string

Yes, you can use the sys module:

import sys
str(sys.argv) # arguments as string

Note that argv[0] is the script name. For more information, take a look at the sys module documentation.


I do not know if it would be the best option, but...

import sys

" ".join(sys.argv)

Will return a string like /the/path/of/file/my_file.py arg1 arg2 arg3


This will work with commands that have space-separated strings in them.

import sys
" ".join("\""+arg+"\"" if " " in arg else arg for arg in sys.argv)

Sample output:

$ python3 /tmp/derp.py "my arg" 1 2 3
python3 /tmp/derp.py "my arg" 1 2 3

This won't work if there's a string argument with a quotation mark in it, to get around that you'd have to delimit the quotes like: arg.replace("\"", "\\\""). I left it out for brevity.