python - shlex preserving double quotes? -


i'm using popen shlex yum command --exclude flag pass list of packages excluded. reason seems shlex not preserving double quotes. pointers how go ?

>>> import shlex >>> x = '/usr/bin/yum update --exclude=\"foo bar baz*\"'    >>> print shlex.split(x) ['/usr/bin/yum', 'update', '--exclude=foo bar baz*'] 

with posix mode off, quotes seem misplaced.

>>> print shlex.split(x,posix=false) ['/usr/bin/yum', 'update', '--exclude="foo', 'bar', 'baz*"'] 

first, parameters arrive correct in target program's argv/argc via normal shlex.split(x) - shown here :

>>> x = '/usr/bin/yum update --exclude=\"foo bar baz*\"'  >>> l = shlex.split(x); l ['/usr/bin/yum', 'update', '--exclude=foo bar baz*'] >>> p = subprocess.popen(['python', '-c', "import sys;print(sys.argv)"] + l, stdout=subprocess.pipe) >>> p.stdout.read() "['-c', '/usr/bin/yum', 'update', '--exclude=foo bar baz*']\r\n" 

: quotes on shell there keeping parameter string correct splitting in target app; , split arguments, split done.


second, can use shell=true on popen , can pass command string unsplit:

p = subprocess.popen(x, shell=true, ...) 

: way string x directly interpreted shell - e.g. bash. shell process involved , consumes resources , run time


third, if want quotes way target program via shlex.split , direct program call, , when have control on input string, can write input string (extra quoting same in shell(-mode)):

>>> x = '/usr/bin/yum update --exclude="\\"foo bar baz*\\""'  >>> l = shlex.split(x); l ['/usr/bin/yum', 'update', '--exclude="foo bar baz*"'] >>> p = subprocess.popen(['python', '-c', "import sys;print(sys.argv)"] + l, stdout=subprocess.pipe) >>> print(p.stdout.read()) ['-c', '/usr/bin/yum', 'update', '--exclude="foo bar baz*"'] 

(note: 1 backslash in input string consume python syntax unless write in r-syntax: x = r'/usr/bin/yum update --exclude="\"foo bar baz*\\""'


fourth, if want given input string quotes target programm, need employ custom shell syntax - e.g. via regex:

>>> x = '/usr/bin/yum update --exclude=\"foo bar baz*\"'  >>> l = re.findall(r'(?:[^\s,"]|"(?:\\.|[^"])*")+', x); l ['/usr/bin/yum', 'update', '--exclude="foo bar baz*"'] >>> p = subprocess.popen(['python', '-c', "import sys;print(sys.argv)"] + l, stdout=subprocess.pipe) >>> print(p.stdout.read()) ['-c', '/usr/bin/yum', 'update', '--exclude="foo bar baz*"'] 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -