기계는 거짓말하지 않는다

Python argparse module 본문

Python

Python argparse module

KillinTime 2021. 8. 28. 15:03

C언어의 getopt와 같은 역할을 하는 명령행 파싱 모듈이다.

콘솔에서 실행할 때 매개변수를 명령어로 지정할 수 있다.

 

add_argument의 default 매개변수는 입력하지 않아도 기본으로 지정되는 값이며 없을 경우 None이다.

help 매개변수는 --help 또는 -h 입력 시 도움말이다.

type 매개변수는 기본 타입을 지정한다. 타입과 다를 경우 에러를 출력한다.

action 매개변수는 True 또는 False를 지정할 수 있다.

import argparse

def parse_opt():
    parser = argparse.ArgumentParser()
    parser.add_argument('--str', type=str, default="String Option", help='string type')
    parser.add_argument('--integer', type=int, default=5, help='integer type')
    # store_false도 가능 store_true일 때 이 옵션을 입력하면 True
    parser.add_argument('--tf', action='store_true', help='true or false type')

    opt = parser.parse_args()
    return opt


def main(opt):
    print(opt.str)
    print(opt.integer)
    print(opt.tf)


if __name__ == "__main__":
    opt = parse_opt()
    main(opt)

위 코드의 파일 이름을 temp.py라고 할 때 python temp.py --명령어로 실행이 가능하다.

python temp.py -h 또는 python temp.py --help를 입력하면 따로 지정하지 않아도 기본으로 도움말을 얻을 수 있다.

 

int 타입에 float 타입을 입력했을 경우

 

python temp.py --tf --str "Other String"

 

 

'Python' 카테고리의 다른 글

Python DataFrame 특정 값 추출  (0) 2021.09.04
Python String에 여러 요소가 있는지 판별  (0) 2021.08.28
Python 파일 이름 변경  (0) 2021.08.19
Python Numpy any Filter  (0) 2021.08.15
Python OpenCV, PIL Image shape, size  (0) 2021.08.10
Comments