Is it possible to patch together a copy-and-pastable invocation for a python program from the invoked program itself? It doesn't have to be exactly the same invocation string, but the arguments should parse to the same thing.
Note that ' '.join(sys.argv)
won't cut it, unfortunately. The main problem I have with this approach is that it won't properly quote arguments. Consider dummy.py
with import sys; print(sys.argv); print(' '.join(sys.argv))
Running python dummy.py "1 2"
prints:
['dummy.py', '1 2']
dummy.py 1 2
And of course if we copy the latter we'll get a different invocation. Wrapping each argument in quotes won't work either. Consider dummy2.py
:
import sys
print(sys.argv)
print(' '.join('"{}"'.format(s) for s in sys.argv))
This will break for:
python dummy2.py ' " breaking " '
Use
shlex.quote
:in shell:
yields:
you may also want to include
sys.executable
, see more detail in the doc.