없다
#!/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
을 사용하는 것이 좋습니다.
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