How to convert argument list to single line command line in Python?

Possible duplicate:
What happens to shlex.split handling?

How to convert a list of command line options like argv to a single line for the command line?

" ".join(argv) not the right solution, since it will not correctly delete lines with spaces.

Example: ./test.py -v --simulate --action removePage --title "AAA BBB"

If you try this, the last argument is AAA BBB without quotes, but if I try to rebuild the command line using a connection, I will get the wrong result.

Note. I know that I can get the command line as a string, but in my case I cannot rely on this, I need a solution that converts the argument list to the correct command line.

+4
source share
2 answers

With Python 3.3, you can try using shlex.quote (sorry, I cannot verify):

 ' '.join(shlex.quote(arg) for arg in argv) 
+1
source

I suppose, if you are not against quoting free of charge:

 " ".join('"%s"'%x.strip().replace('"',r'\"') for x in lst) 
0
source

Source: https://habr.com/ru/post/1444880/


All Articles