2014-03-12 25 views
1

我有一个python脚本,它从命令行参数中获取输入。例如:“取消引用”/解析Python中的bash参数字符串

./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 
+0

注意,这是什么'xargs'做到了,原来是这是一个可怕的设计决定,人们在30年后仍然受苦。人们普遍认为'\ 0'终止的字符串,或者至少'\ n'终止,是要走的路。 –

回答

4

你想shlex.split()

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

import shlex 

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