YGA*_*YGA 32 python shell quoting
Python标准库中是否有任何内容可以正确解析/解析字符串以便在shell命令中使用?我正在寻找perl的python模拟String::ShellQuote::shell_quote:
$ print String::ShellQuote::shell_quote("hello", "stack", "overflow's", "quite", "cool")
hello stack 'overflow'\''s' quite cool
Run Code Online (Sandbox Code Playgroud)
而且,更重要的是,它会在相反的方向上起作用(取一个字符串并将其分解为一个列表).
YGA*_*YGA 29
好像
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"'
Run Code Online (Sandbox Code Playgroud)
让我足够远.
pipes.quote现在是shlex.quote在python 3中.使用那段代码很容易.
https://github.com/python/cpython/blob/master/Lib/shlex.py#L281
该版本正确处理零长度参数.
我很确定pipes.quote已经坏了,不应该使用,因为它没有正确处理零长度参数:
>>> from pipes import quote
>>> args = ['arg1', '', 'arg3']
>>> print 'mycommand %s' % (' '.join(quote(arg) for arg in args))
mycommand arg1 arg3
Run Code Online (Sandbox Code Playgroud)
我相信结果应该是这样的
mycommand arg1 '' arg3
Run Code Online (Sandbox Code Playgroud)
小智 5
对于shell引用,这是有效的:我在Posix上进行了严格的测试.[我假设list2cmdlinePython提供的函数与Windows上宣传的一样工作]
# shell.py
import os
if os.name == 'nt':
from subprocess import list2cmdline
def quote(arg):
return list2cmdline([arg])[0]
else:
import re
_quote_pos = re.compile('(?=[^-0-9a-zA-Z_./\n])')
def quote(arg):
r"""
>>> quote('\t')
'\\\t'
>>> quote('foo bar')
'foo\\ bar'
"""
# This is the logic emacs uses
if arg:
return _quote_pos.sub('\\\\', arg).replace('\n',"'\n'")
else:
return "''"
def list2cmdline(args):
return ' '.join([ quote(a) for a in args ])
Run Code Online (Sandbox Code Playgroud)
如果有人关心,测试就在这里.