2014-10-17 2 views
3

문자열을 인수와 플래그를 수동으로 구문 분석하려고합니다. 예를 들어Python에서 플래그를 파싱

, 내가 다시

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

문자열의 플래그의 임의의 수에 대한 얻을 것으로 기대하고 문자열을

"--flag1 'this is the argument'"

이있는 경우.

어려운 점은 다중 단어 플래그 인수를 처리하는 방법을 결정하는 것입니다. 내가 할 경우

예를 들어,

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

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

내가 기대하지 않은

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

된다 (parserargparse에서 온다). 이 작업을 수행하는 간단한 방법이 있습니까?

답변

8

운이 좋았습니다. 거기에 입니다. shlex.split을 사용하십시오. 원하는대로 문자열을 분할해야합니다.

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

파이썬, 배터리 포함 ... :-) – thefourtheye

+0

어쨌든 대부분의 크기 :-) – mgilson

관련 문제