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).
pipes.quote
is nowshlex.quote
in python 3. It is easy enough to use that piece of code.https://github.com/python/cpython/blob/master/Lib/shlex.py#L281
That version handles zero-length argument correctly.
You should never have to shell quote. The correct way to do a command is to not do shell quoting and instead use subprocess.call or subprocess.Popen, and pass a list of unquoted arguments. This is immune to shell expansion.
i.e.
If you want to unquote shell quoted data, you can use shlex.shlex like this: