Python模块到shellquote/unshellquote?

2024-09-27 19:11:40 发布

您现在位置:Python中文网/ 问答频道 /正文

python标准库中是否有任何内容可以正确解析/断开字符串以用于shell命令?我正在寻找与perl的String::ShellQuote::shell_quote类似的python:

$ print String::ShellQuote::shell_quote("hello", "stack", "overflow's", "quite", "cool")
hello stack 'overflow'\''s' quite cool

而且,更重要的是,一些工作方向相反的东西(取一个字符串并将其分解成一个列表)。


Tags: 字符串命令内容hello标准stringstackshell
3条回答

我很确定pipes.quote已损坏,不应使用,因为它无法正确处理零长度参数:

>>> from pipes import quote
>>> args = ['arg1', '', 'arg3']
>>> print 'mycommand %s' % (' '.join(quote(arg) for arg in args))
mycommand arg1  arg3

我相信结果应该是

mycommand arg1 '' arg3

看起来像

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"'

让我走得够远。

在python 3中,pipes.quote现在是shlex.quote。 使用这段代码很容易。

https://github.com/python/cpython/blob/master/Lib/shlex.py#L281

该版本正确处理零长度参数。

相关问题 更多 >

    热门问题