2014-03-12 31 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']