Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-creating a python invocation

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 " '
like image 558
VF1 Avatar asked Dec 06 '17 05:12

VF1


1 Answers

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.

like image 93
georgexsh Avatar answered Nov 24 '22 07:11

georgexsh