#Python argparse 공식 문서를 참조했다.
커맨드라인 인터페이스를 갖는 프로그램을 만들 때, 자주 사용되는 것은 역시나 command line arguments다. C에 optget()
이 있다면, Python은 argparse
가 있다.
자질구레한 작은 예제 말고 큰 예제로 한눈에 사용법을 익혀보자.
##Cheat Sheet
###코드
import argparse
parser = argparse.ArgumentParser(description="Simple 'argparse' demo application")
# Ordinary>
parser.add_argument("MAKERJ_PATH")
parser.add_argument("choiceable", choices=['a','b','c'], help="select from one of the choice options")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
# Mutually exclusive> user must select only ONE option from group (at this time, -v and -q)
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
args = parser.parse_args()
answer = args.x**args.y
if args.quiet:
print(answer)
elif args.verbose:
print("{} to the power {} equals {}".format(args.x, args.y, answer))
else:
print("{}^{} == {}".format(args.x, args.y, answer))
참고
parser.parse_args()
를 호출하는 순간, 작성한ArgumentParser
가 프로그램에 붙는다.
argument의 타입은 크게 3가지가 있다:
- 필수:
add_argument
에 이름만 적은 경우. 예를 들어, mandatory - 선택적:
add_argument
에 - 또는 --를 적고 이름을 적은 경우. 예를 들어, --myoptional - 단일 선택:
add_mutually_exclusive_group()
으로 그룹을 만들고, 해당 그룹에 추가된 매개변수는 단 하나만 선택해야 한다.