【问题标题】:"Unquote"/parse bash argument string in python“取消引用”/解析python中的bash参数字符串
【发布时间】:2014-03-12 12:31:39
【问题描述】:

我有一个从命令行参数获取输入的 python 脚本。例如:

./myscript.py first_item second\ item "third item"

我可以使用pipes.quote 输出单独的项目并转义空格和特殊字符。

print " ".join(map(pipes.quote, outputItems))

是否有任何现有的“unquote”接口可以解析 bash 参数字符串,保持转义空格和引号字符串完整?

允许同一个 python 脚本处理这个的东西:

echo 'first_item second\ item "third item"' | ./myscript.py

【问题讨论】:

  • 请注意,这就是xargs 所做的,结果证明这是一个可怕的设计决策,30 年后人们仍在遭受痛苦。人们普遍认为\0 终止字符串,或者至少\n 终止,是要走的路。

标签: python bash escaping


【解决方案1】:

你想要shlex.split():

s = 'first_item second\ item "third item"'

import shlex

shlex.split(s)
Out[3]: ['first_item', 'second item', 'third item']

【讨论】:

    猜你喜欢
    • 2011-03-03
    • 2013-03-29
    • 2016-07-30
    • 2017-07-16
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    相关资源
    最近更新 更多