2013-02-04 3 views
15

쉼표로 구분 된 정수 목록을 포함하는 필수 위치 인수를 구문 분석하고 싶습니다. 나는 사람들이 플래그 문자로 - 외에 다른 문자를 사용하는 것이 좋습니다 본 적이argparse를 사용하여 마이너스 기호 (음수)로 위치 인수를 구문 분석하는 방법

import argparse 
parser = argparse.ArgumentParser() 
parser.add_argument('positional') 
parser.add_argument('-t', '--test', action='store_true') 
opts = parser.parse_args() 
print opts 

$ python example.py --test 1,2,3,4 
Namespace(positional='1,2,3,4', test=True) 

$ python example.py --test -1,2,3,4 
usage: example.py [-h] [-t] positional 
example.py: error: too few arguments 

$ python example.py --test "-1,2,3,4" 
usage: example.py [-h] [-t] positional 
example.py: error: too few arguments 

,하지만 난 오히려 그렇게하지 않는 게 좋을 : - 첫번째 정수 선도적 마이너스가 포함되어있는 경우 ('')는 기호, argparse는 불평 . --test-1,2,3,4을 모두 유효한 인수로 허용하는 argparse를 구성하는 또 다른 방법이 있습니까?

+2

- 누군가가 이것을 필요로하는 경우에 --test가 인수를하면 다음을 할 수 있습니다 : 'python example.py - test = -1,2,3,4' – lababidi

답변

21

당신은 당신의 명령 줄 인수로 --를 삽입해야합니다

$ python example.py --test -- -1,2,3,4 
Namespace(positional='-1,2,3,4', test=True) 

이중 대시 argparse 더 이상 선택 스위치를 찾고 중지; 이것은 명령 행 도구에 대한이 사용 사례를 정확하게 다루는 표준 방법입니다. documentation에서

+0

아, 나는 '표준 '이중 대시 (아직도 배우고있는 일종의 nix 초보자 (아직도 배우는 것) ...)를 사용해야하는 것 정보에 감사드립니다! – Inactivist

+1

그저'error : unrecognized arguments : --' (Python 2.7.3에서는 argparse)를 제공합니다. – panzi

+1

@panzi : Python 2.7.5에서는 이러한 문제가 없습니다. –

8

: -1,2,3,4 이후

The parse_args() method attempts to give errors whenever the user has clearly made a mistake, but some situations are inherently ambiguous. For example, the command-line argument -1 could either be an attempt to specify an option or an attempt to provide a positional argument. The parse_args() method is cautious here: positional arguments may only begin with - if they look like negative numbers and there are no options in the parser that look like negative numbers:

가하는 당신이 * 대부분의 유닉스 계열의 시스템에서와 같이 --와 함께 "탈출"해야 음수 같은 하지보세요.

#test.py 
import argparse 

parser = argparse.ArgumentParser() 
parser.add_argument('positional', nargs='*') #'+' for one or more numbers 

print parser.parse_args() 

출력 :

$ python test.py -1 2 3 -4 5 6 
Namespace(positional=['-1', '2', '3', '-4', '5', '6']) 

세 번째 방법은 당신이 원하는 것을 얻기 위해 사용되는

타 솔루션은 위치에 대한 nargs를 사용하여 공간이 분리로 숫자를 통과하는 것 parse_args 대신 parse_known_args입니다. 당신은 파서에 위치 인수를 추가하는 대신 수동으로 분석하지 않습니다

import argparse 

parser = argparse.ArgumentParser() 
parser.add_argument('--test', action='store_true') 

parsed, args = parser.parse_known_args() 
print parsed 
print args 

결과 :

$ python test.py --test -1,2,3,4            
Namespace(test=True) 
['-1,2,3,4']  

이 도움말 텍스트가 적은 정보가 될 단점이있다.

+0

설명서를 보았지만 표준 동작을 변경하는 트릭이 있는지 궁금합니다. 이 시점에서 나는'-'이스케이프 메커니즘을 사용하는 것보다 4 개의 분리 된 위치 인수를 요구하거나 스페이스 구분 기호를 사용하는 것이 더 나을 것이라고 생각한다. 도와 주셔서 감사합니다. – Inactivist

+0

@Inactivist '-1,2,3,4' 스타일의 위치를 ​​허용하는 세 번째 방법으로 내 대답을 업데이트했습니다. – Bakuriu