2014-02-10 3 views
0

명령 줄 구문 분석에 getopts을 사용하려고합니다. 그러나 옵션을 : 또는 =을 통해 필수 인수로 설정하고 명령 줄에 인수를 지정하지 않으면 다음 옵션이 첫 번째 옵션의 인수로 사용됩니다. 대신 오류를 제기하고 싶습니다. 이 문제를 어떻게 해결할 수 있습니까?첫 번째 옵션의 인수로 두 번째 옵션을 사용하는 Python getopt

작동 예 : 다음과 같은 출력

python getopt_test.py --config-file --sample-list 

결과 (opts) : 아무것도

[('--config-file', '--sample-list')] 
+2

getopt 대신 [argparse] (http://docs.python.org/2.7/library/argparse.html)를 사용하십시오. [getopt] (http://docs.python.org/ 2.7/library/getopt.html) : * C getopt() 함수에 익숙하지 않거나 더 적은 코드를 작성하고 더 나은 도움말과 오류 메시지를 얻으려는 사용자는 대신 argparse 모듈 사용을 고려해야합니다. * – zmo

답변

0

없다

#!/usr/bin/env python 

import sys, getopt, warnings 


argv = sys.argv 

try: 
    opts, args = getopt.getopt(argv[1:], "c:", ["config-file=", "sample-list="]) 
    print >> sys.stderr, opts 

except getopt.GetoptError as msg: 
    print msg 

과 같이 명령 행에서이 스크립트를 실행 실행 중 잘못 :

당신의 조각에서210
python getopt_test.py --config-file --sample-list 

:

opts, args = getopt.getopt(argv[1:], "c:", ["config-file=", "sample-list="]) 

# config-file requires argument i.e what ever argument come next in sys.argv list 
# sample-list requires argument i.e what ever argument come next in sys.argv list 

그래서, 당신은

--sample 목록 그냥 --config 파일에 인수하고, python getopt_test.py --config-file --sample-list로 실행할 때.

터렛 내부에 첫 번째 요소를 포함하는 튜플 요소의 목록 인 옵션 파일을 옵션 이름으로, 두 번째 요소를 인수로 사용하여 확인합니다.

tmp/: python get.py --config-file --sample-list 
[('--config-file', '--sample-list')] [] 
tmp/: 

# lets put a proper argument for config-file 
tmp/: python get.py --config-file 'argument_for_config_file' 
[('--config-file', 'argument_for_config_file')] [] 
tmp/: 

# Lets run with proper sample-list 
tmp/: python get.py --config-file 'argument_for_config_file' --sample-list 'here is the 
list' 
[('--config-file', 'argument_for_config_file'), ('--sample-list', 'here is the list')] 
[] 
tmp/: 

따라서 사용자가 올바른 옵션과 인수를 제공 할 수 있도록 적절한 구문 분석을 작성해야합니다. optparse를 사용하는 경우. 예외에 대한

: 예외 getopt.GetoptError

없는 옵션이 인수 목록 또는 인수를 필요로하는 옵션 이 주어 없음에서 발견되는 경우가 발생합니다.하지만 귀하의 경우에는 아무 규칙없이 침해당한 이유가 무엇이든 위반하지 않았습니다.

이 모든 optparse의 함정 방지하려면 고도의 모든 문제를 해결하기 위해 새로운 좋은 기능의 톤을 가지고 argparse을 사용하는 것이 좋습니다.

+0

getopt가 "-"로 시작하는 것을 옵션에 대한 인수로 생각하지 않으므로 인수가 없기 때문에 오류가 발생합니다. – MarlinaH

+0

getopt 구문 분석 sys.argv의 자세한 내용은 여기를 참조하십시오. http://hg.python.org/cpython/file/2.7/Lib/getopt.py#l144 –

관련 문제