Re-creating python call

Is it possible to copy joint copy and passive call for python program from the called program itself? It does not have to be exactly the same call string, but the arguments must parse the same thing.

Please note that ' '.join(sys.argv) , unfortunately, will not cut. The main problem I am facing is that it will not correctly indicate the arguments. Consider dummy.py with import sys; print(sys.argv); print(' '.join(sys.argv)) import sys; print(sys.argv); print(' '.join(sys.argv))

Executing python dummy.py "1 2" fingerprints:

 ['dummy.py', '1 2'] dummy.py 1 2 

And, of course, if we copy the latter, we will receive another challenge. Wrapping each argument in quotation marks will also not work. 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 " ' 
+7
python shell escaping shlex
source share
1 answer

Use shlex.quote :

 import sys from shlex import quote print(' '.join(quote(s) for s in sys.argv)) 

in the shell:

 python space_in_argv.py "aa bb" ' " breaking " ' 

gives:

 space_in_argv.py 'aa bb' ' " breaking " ' 

you can also enable sys.executable , see the document for more details .

+6
source share

All Articles