getopt
— 명령 줄 옵션용 C 스타일 구문 분석기¶
소스 코드: Lib/getopt.py
참고
This module is considered feature complete. A more declarative and
extensible alternative to this API is provided in the optparse
module. Further functional enhancements for command line parameter
processing are provided either as third party modules on PyPI,
or else as features in the argparse
module.
이 모듈은 스크립트가 sys.argv
에 있는 명령 줄 인자를 구문 분석하는 데 도움이 됩니다. 유닉스 getopt()
함수와 같은 규칙을 지원합니다 (’-
’ 와 ‘--
’ 형식의 인자의 특수한 의미를 포함합니다). 선택적인 세 번째 인자를 통해 GNU 소프트웨어가 지원하는 것과 유사한 긴 옵션을 사용할 수 있습니다.
Users who are unfamiliar with the Unix getopt()
function should consider
using the argparse
module instead. Users who are familiar with the Unix
getopt()
function, but would like to get equivalent behavior while
writing less code and getting better help and error messages should consider
using the optparse
module. See Choosing an argument parsing library for
additional details.
이 모듈은 두 가지 함수와 예외를 제공합니다:
- getopt.getopt(args, shortopts, longopts=[])¶
명령 줄 옵션과 매개 변수 목록을 구문 분석합니다. args는 실행 중인 프로그램에 대한 앞머리 참조를 포함하지 않는, 구문 분석할 인자 리스트입니다. 일반적으로, 이는
sys.argv[1:]
를 의미합니다. shortopts는 스크립트가 인식하고자 하는 옵션 문자의 문자열이며, 인자를 요구하는 옵션은 뒤에 콜론(':'
; 즉, 유닉스getopt()
가 사용하는 것과 같은 형식)이 필요합니다.참고
GNU
getopt()
와는 달리, 옵션이 아닌 인자 다음에 오는 모든 인자는 옵션이 아닌 것으로 간주합니다. 이는 비 GNU 유닉스 시스템이 작동하는 방식과 비슷합니다.지정되면, longopts는 지원되어야 하는 긴 옵션의 이름을 가진 문자열 리스트여야 합니다. 선행
'--'
문자는 옵션 이름에 포함되지 않아야 합니다. 인자가 필요한 긴 옵션 뒤에는 등호('='
)가 와야 합니다. 선택적 인자는 지원되지 않습니다. 긴 옵션만 허용하려면, shortopts는 빈 문자열이어야 합니다. 명령 줄에서 긴 옵션은 허용된 옵션 중 하나와 정확히 일치하는 옵션 이름의 접두사를 제공하는 한 인식 할 수 있습니다. 예를 들어, longopts가['foo', 'frob']
면--fo
옵션은--foo
로 일치하지만,--f
는 유일하게 일치하지 않으므로GetoptError
가 발생합니다.반환 값은 두 요소로 구성됩니다: 첫 번째는
(option, value)
쌍의 리스트입니다; 두 번째는 옵션 리스트가 제거된 후 남겨진 프로그램 인자 리스트입니다 (이것은 args의 후행 슬라이스입니다). 반환된 각 옵션-값 쌍은 첫 번째 요소로 옵션을 가지며, 짧은 옵션(예를 들어,'-x'
)은 하이픈이, 긴 옵션(예를 들어,'--long-option'
)은 두 개의 하이픈이 접두사로 붙고, 두 번째 요소는 옵션 인자나 옵션에 인자가 없으면 빈 문자열입니다. 옵션은 발견된 순서와 같은 순서로 리스트에 나타나므로, 여러 번 나오는 것을 허용합니다. 긴 옵션과 짧은 옵션은 혼합될 수 있습니다.
- getopt.gnu_getopt(args, shortopts, longopts=[])¶
이 함수는 기본적으로 GNU 스타일 스캔 모드가 사용된다는 점을 제외하고는
getopt()
처럼 작동합니다. 이것은 옵션과 옵션이 아닌 인자가 섞일 수 있음을 뜻합니다.getopt()
함수는 옵션이 아닌 인자가 발견되자마자 옵션 처리를 중지합니다.옵션 문자열의 첫 번째 문자가
'+'
이거나, 환경 변수POSIXLY_CORRECT
가 설정되면, 옵션이 아닌 인자를 만나자마자 옵션 처리가 중지됩니다.
- exception getopt.GetoptError¶
인자 목록에 인식할 수 없는 옵션이 있거나 인자가 필요한 옵션에 아무것도 주어지지 않으면 발생합니다. 예외에 대한 인자는 에러의 원인을 나타내는 문자열입니다. 긴 옵션의 경우, 인자를 요구하지 않는 옵션에 인자가 주어질 때도 이 예외를 발생시킵니다. 어트리뷰트
msg
와opt
는 에러 메시지와 관련 옵션을 제공합니다; 예외와 관련된 특정 옵션이 없으면opt
는 빈 문자열입니다.
- exception getopt.error¶
GetoptError
의 별칭; 과거 호환성을 위한 것입니다.
유닉스 스타일 옵션만 사용하는 예제:
>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
긴 옵션 이름을 사용하는 것도 똑같이 간단합니다:
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
... 'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
>>> args
['a1', 'a2']
스크립트에서, 일반적인 사용법은 다음과 같습니다:
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError as err:
# 도움말 정보를 출력하고 종료합니다:
print(err) # "option -a not recognized" 같은 것을 출력합니다
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-o", "--output"):
output = a
else:
assert False, "unhandled option"
process(args, output=output, verbose=verbose)
if __name__ == "__main__":
main()
optparse
모듈을 사용하면 더 적은 코드로, 더욱 유용한 도움말과 에러 메시지를 제공하는 동등한 명령 줄 인터페이스를 만들 수 있습니다:
import optparse
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-o', '--output')
parser.add_option('-v', dest='verbose', action='store_true')
opts, args = parser.parse_args()
process(args, output=opts.output, verbose=opts.verbose)
이 경우와 거의 동등한 명령 줄 인터페이스를 argparse
모듈을 사용해서도 만들 수 있습니다:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output')
parser.add_argument('-v', dest='verbose', action='store_true')
parser.add_argument('rest', nargs='*')
args = parser.parse_args()
process(args.rest, output=args.output, verbose=args.verbose)
See Choosing an argument parsing library for details on how the argparse
version of this code differs in behaviour from the optparse
(and
getopt
) version.