这个问题已经有一个答案在这里:

有什么Python标准图书馆,这将正确解析/unparse字符串中使用的壳的命令吗?我在寻找python模perl's String::ShellQuote::shell_quote:

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

而且,更重要的是,这东西会工作在反方向(采取一串并分解成一个列表)。

有帮助吗?

解决方案

pipes.quote 是现在 shlex.quote 在python3.这是很容易使用的那个代码。

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

该版本处理长度为零的说法是否正确。

其他提示

看起来像

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

让我远远不够的。

我敢肯定,管道。报价是破碎的,而不应被使用,因为它并不能处理长度为零的论点的正确:

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

我认为,结果应该是这样的

mycommand arg1 '' arg3

为壳的报价,这一工作:我已经经过严格测试,它对Posix.[我假设的 list2cmdline 功能提供的蟒蛇的工作上宣传的窗口]

# 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 ])

测试 在这里,, 如果有人问津。

来引文结束,尝试 shlex.split()

你不应该壳的报价。正确的方式做到的命令是不要做壳引用和使用 子流程.呼叫子流程.Popen, ,并通过一个列表中没有引用的论点。这是免疫壳的扩展。

subprocess.Popen(['echo', '"', '$foo'], shell=False)

如果你想引文结束壳援引的数据,可以使用 shlex.shlex 是这样的:

list(shlex.shlex("hello stack 'overflow'\''s' quite cool"))

标准图书馆模块子流程具有list2cmdline功能做到这一点,尽管根据 Microsoft规则 所以我不知道该如何可靠它的工作在类Unix系统的环境更加复杂的命令行。

quote功能可用于相当一段时间(Python2.7?) --主要缺点是它从 pipe 模块 shlex 之间的3.2和3.3.

你必须准备处理这两种情况同时进,功能:

try:
    from shlex import quote
except ImportError:
    from pipes import quote
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top