Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python module to shellquote/unshellquote? [duplicate]

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).

like image 686
10 revs, 7 users 53% Avatar asked Jun 08 '09 22:06

10 revs, 7 users 53%


2 Answers

Looks like

try:  # py3     from shlex import quote except ImportError:  # py2     from pipes import quote  quote("hello stack overflow's quite cool") >>> '"hello stack overflow\'s quite cool"' 

gets me far enough.

like image 83
10 revs, 7 users 53% Avatar answered Sep 22 '22 08:09

10 revs, 7 users 53%


pipes.quote is now shlex.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.

like image 39
dnozay Avatar answered Sep 22 '22 08:09

dnozay