This question already has an answer here:
- How to escape os.system() calls? 10 answers
Is there anything in the Python standard library that will properly parse/unparse strings for using in shell commands? I'm looking for the python analog to perl's String::ShellQuote::shell_quote
:
$ print String::ShellQuote::shell_quote("hello", "stack", "overflow's", "quite", "cool")
hello stack 'overflow'\''s' quite cool
And, even more importantly, something which will work in the reverse direction (take a string and decompose it into a list).
For shell quoting, this works: I've rigorously tested it on Posix. [I'm assuming that the
list2cmdline
function supplied by Python works as advertised on Windows]The tests are here, if anyone cares.
I'm pretty sure that pipes.quote is broken, and should not be used, because it does not handle zero-length arguments correctly:
I believe the result should be something like
The standard library module subprocess has the list2cmdline function which does this, albeit according to Microsoft rules so I am not sure how reliable it works in Unix-like environments for more complicated command lines.
To unquote, try
shlex.split()
The
quote
function is available for quite some time (Python 2.7?) -- the major drawback is it moved frompipe
module toshlex
between 3.2 and 3.3.You have to be prepared to handle both cases while importing that function:
Looks like
gets me far enough.