Python模块用于shell引号/去引号?
在Python的标准库里,有没有什么工具可以正确处理字符串,以便在命令行中使用?我想找一个和perl里的String::ShellQuote::shell_quote
功能相似的东西:
$ print String::ShellQuote::shell_quote("hello", "stack", "overflow's", "quite", "cool")
hello stack 'overflow'\''s' quite cool
还有,更重要的是,是否有可以反向操作的工具(也就是把一个字符串拆分成一个列表)。
8 个回答
10
要去掉引号,可以试试 shlex.split()
这个方法。
33
看起来
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"'
已经让我走得够远了。
11
pipes.quote
在 Python 3 中变成了 shlex.quote
。使用这段代码其实很简单。
https://github.com/python/cpython/blob/master/Lib/shlex.py#L281
这个版本能够正确处理长度为零的参数。