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
:
import sys
from shlex import quote
print(' '.join(quote(s) for s in sys.argv))
in shell:
python space_in_argv.py "aa bb" ' " breaking " '
yields:
space_in_argv.py 'aa bb' ' " breaking " '
you may also want to include sys.executable
, see more detail in the doc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With