2014-10-17 51 views
3

我想手動解析出給定字符串的參數和標誌。解析Python中的標誌

舉例來說,如果我有一個字符串

"--flag1 'this is the argument'"

我期待回到

['--flag1', 'this is the argument']

爲標誌的字符串中的任意號碼。

我遇到的困難是確定如何處理多字標誌參數。

例如,如果我這樣做(parser來自​​)

parser.parse_args("--flag1 'this is the argument'".split())

"--flag1 'this is the argument'".split()"

成爲

['--flag1', "'this", 'is', 'the', "argument'"]

這不是我所期望的。有沒有簡單的方法來做到這一點?

回答

8

你很幸運;有一個簡單的方法來做到這一點。使用shlex.split。它應該根據需要分割字符串。

>>> import shlex 
>>> shlex.split("--flag1 'this is the argument'") 
['--flag1', 'this is the argument'] 
+2

Python,包括電池... :-) – thefourtheye 2014-10-17 20:25:11

+0

反正大多數尺寸:-) – mgilson 2014-10-17 20:25:48