argparse로 CLI argument, flag 구현
2021. 11. 12. 13:20
SBSE TSP solver 과제할 때 사용한 코드
import argparse parser = argparse.ArgumentParser() parser.add_argument('file', type=argparse.FileType('r')) parser.add_argument('-v', required=False, default=False, action='store_true', help='print out progress') # T/F flag parser.add_argument('-m', required=False, default=False, action='store_true', help='add flag to use 3-opt instead of 2-opt') # T/F flag parser.add_argument('-p', required=False, default=-1, type=int, help='population size (NOT USED IN CURRENT LOCAL SEARCH METHOD)') # num value flag parser.add_argument('-f', required=False, default=1000, type=int, help='limit the total number of fitness evaluations') # num value flag args = parser.parse_args() args_dic = vars(args) config.VERBOSE = args_dic['v'] config.USE_THREE_OPT = args_dic['m'] config.POP_SIZE = args_dic['p'] # -p option - population size (NOT USED IN CURRENT METHOD - LOCAL SEARCH) config.FITNESS_CNT = args_dic['f'] # -f option - fitness evaluation limit print(args, type(args), args_dic) #ifdef DBG # python main.py rl11849.tsp -v -m -p 100 -f 2000
required : 필수 flag인지
default : 기본 값
type : 값의 type
action : 어떤 식으로 값 받을 건지 (여러 종류 있음)
number flag
parser.add_argument('-n', required=False, default=1000, type=int, \ help='limit the total number of fitness evaluations')
boolean flag
parser.add_argument('-v', required=False, default=False, action='store_true', help='T/F flag')
file argument
https://stackoverflow.com/questions/18862836/how-to-open-file-using-argparse
# python main.py file.txt parser.add_argument('file', type=argparse.FileType('r')) args = parser.parse_args() args.file # file.txt
'<언어> > [Python]' 카테고리의 다른 글
[Python] implementation 이해 (CPython, Jython, PyPy, ...) (0) | 2022.01.26 |
---|---|
[Python] 메모리 관리 (memory allocation) (0) | 2022.01.26 |
lambda scope capture 주의할 점 (0) | 2021.09.10 |
[Generator] yield, yield from (0) | 2021.08.24 |
[Tesseract][OpenCV] 코드 이미지 OCR + 자동 indent (0) | 2021.07.10 |