"取消引用" /解析python中的bash参数字符串

时间:2014-03-12 12:31:40

标签: python bash escaping

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

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

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

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

是否存在将解析bash参数字符串的现有“unquote”接口,保持转义空格和带引号的字符串不变?

允许相同的python脚本处理此事的东西:

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

1 个答案:

答案 0 :(得分:4)

您想要shlex.split()

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

import shlex

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