4

Possible Duplicate:
What’s the reverse of shlex.split?

How do I convert a list of command line parameters, like argv to a single string for command line?

" ".join(argv) is not the correct solution as it will not escape the strings with spaces correctly.

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 with join I will get a wrong result.

Note: I know that I can get the command line as a string, but in my case I cannot rely on that, I need a solution that converts a list of arguments to a proper command line.

Community
  • 1
  • 1
sorin
  • 161,544
  • 178
  • 535
  • 806

2 Answers2

2

With Python 3.3 you can try using shlex.quote (sorry, I can't check):

' '.join(shlex.quote(arg) for arg in argv)
Nicolas
  • 5,583
  • 1
  • 25
  • 37
0

I suppose if you don't mind gratuitous quoting:

" ".join('"%s"'%x.strip().replace('"',r'\"') for x in lst)
mgilson
  • 300,191
  • 65
  • 633
  • 696