[Python] argparse 모듈 사용하기.

2023. 4. 5. 15:08·Programming
728x90
728x90

https://wellsr.com/python/passing-command-line-arguments-in-python-with-argparse/

 

argparse 모듈

Python에서 기본적으로 제공하는 명령어 인자 파서 모듈이다.

 

command line inerface 으로 프로그램을 만들 때 기본적으로 필요하다.

linux 쪽 경험이 풍부한 이들에겐 getopt가 보다 익숙하지만 그런 사람이면, 이런 문서가 필요없다.

(이런 것이 익숙한 이들하고 일하는 경우가 점점 더 없음.)

 

자세하게 공부하고 싶다면 다음을 참고:

https://ds31x.tistory.com/518

 

CLI Program에서의 arguments - argparse모듈

0. CLI(Command Line Interface) Program (=CLI 명령어)에서 사용되는 arguments 대한 주요 용어Command: 실행할 프로그램/스크립트 이름.예) python, git, lsParameter: 명령 뒤에 오는 모든 인자의 총칭POSIX용어에선 Parame

ds31x.tistory.com


예제코드

다음 코드를 참고하라.

# coding: utf-8
import argparse 

def set_config():
    # ArgumentParser 객체 생성
    parser = argparse.ArgumentParser(
        prog=sys.argv[0],  # 현재 실행된 파일명을 help 메시지에 표시
        description="This program is an example to show how to use argparse!",
        epilog="""Examples of usage:
  python %(prog)s 어찌고 저찌고     # 특정 실행예
""",  # help 메시지의 끝부분에 추가 설명이나 사용예 출력
        formatter_class=argparse.RawDescriptionHelpFormatter
        # RawDescriptionHelpFormatter를 써야 epilog에서 줄바꿈 그대로 출력됨
    )

    # 반드시 프로그램 수행시 요구되는 optioin 설정은 positional argument로 
    # 처리하면 가장 쉽다.
    # - 아래의 arg0의 경우 positional argument이며 반드시 넘겨져야 함.
    # - 수행시 넘겨지지 않으면 error발생.
    parser.add_argument('arg0', help='required argment!')

    # 선택적으로 입력할 option (or argument)은 다음과 같이 설정가능함.
    # - `--arg1 input_arg` 와 같이 필수 option 이후에서 추가적으로 기재.
    # - 입력을 안해도 에러나지 않음. 입력 안하면 None이 할당됨.
    # - 하이픈이 2개 연속으로 주어진 경우, 풀네임으로 option 이름을 기재하고,
    #   하이픈이 1개인 경우로 시작하는 경우는 약어로 한 문자로 option를 나타냄. 
    parser.add_argument('--arg1', '-a', help='optionial argment!')

    # option인 argumnet도 다음과 같이 필수로 바꿀 수 있음.
    parser.add_argument('--req_arg', required=True)

    # optional argument의 경우 default 값을 할당할 수도 있음.
    parser.add_argument('--arg2', default='def_arg2',
                        help='required argment! default="def_arg2"')

    # option에 해당하는 attribute 명은 기본적으로 argument name (or option name)으로
    # 하이픈을 뺀 문자열이 되지만, `dest` parameter를 사용하여 지정가능함.
    # parser.add_argument('--dst_arg', action='store', dest='data')
    parser.add_argument('--dst_arg', dest='data')


    # 기본적으로 argument는 string이나, type을 지정할 수도 있음.
    parser.add_argument('--arg3', '-i', type=int,
                        default=0, 
                        help='optional int type arg!')

    # type을 함수로 지정하여, 여러 값들을 구분자로 구분하여 입력하고 
    # list로 받을 수도 있음.
    comma_parse = lambda arg: list(map(float, arg.split(',')))
    parser.add_argument('--flist', type=comma_parse,
                        help='3,2,3 -> [3.,2.,3.]')

    # space를 구분자로 여러개를 입력하려면, nargs를 통해 입력받을 갯수를 
    # 지정하면 된다. 만약 nargs가 *이며 가변형이 됨.
    parser.add_argument('--multiargs', nargs=2)

    # option의 값을 제한하려면 다음을 이용.
    # `--help` 로 선택가능한 값을 확인할 수 있음.
    # "--limited_arg {0,1}" 형태로 출력됨.
    parser.add_argument('--limited_arg', choices=['0','1'])

    # 사실 command line에서 option들의 상당수는 flag모드로 동작한다.
    # 값을 입력받는 게 아닌 해당 option 명만 지정하면, True로, 아니면 False로 
    # 동작하는 방법임.
    # - 아래와 같이 action='store_true`로 지정시 해당 option이 입력되면 True값을 가짐.
    parser.add_argument("--flag", "-f", action='store_true', 
                        help="enable verbosity" )

    return parser

if __name__ == '__main__':

    parser = set_config()
    args = parser.parse_args()

    # argparse의 args 객체에서 입력된 argument들에 접근은 argument의 풀네임으로 접근.
    print(args.arg0, args.arg1)

    # 모든 구성 varaible을 보여주는 vars와
    # 특정 객체에서 attribute를 두번째 argment에 해당 attribute의 이름의 문자열로
    # 얻어오는 getattr 와 같은
    # 내장함수로 argument들을 출력하는 부분.
    for idx, a in enumerate(sorted(vars(args))):
        attr = getattr(args, a)
        print(f'[{idx:02d}] {a} : {attr}')

References

https://ds31x.tistory.com/518

 

CLI Program에서의 arguments - argparse모듈

0. CLI(Command Line Interface) Program (=CLI 명령어)에서 사용되는 arguments 대한 주요 용어Command: 실행할 프로그램/스크립트 이름.예) python, git, lsParameter: 명령 뒤에 오는 모든 인자의 총칭POSIX용어에선 Parame

ds31x.tistory.com

argparse — 명령행 옵션, 인자와 부속 명령을 위한 파서

 

argparse — Parser for command-line options, arguments and subcommands

Source code: Lib/argparse.py Tutorial: This page contains the API reference information. For a more gentle introduction to Python command-line parsing, have a look at the argparse tutorial. The arg...

docs.python.org

Argparse Tutorial

 

Argparse Tutorial

author, Tshepang Mbambo,. This tutorial is intended to be a gentle introduction to argparse, the recommended command-line parsing module in the Python standard library. Concepts: Let’s show the sor...

docs.python.org

Comparing Python Command-Line Parsing Libraries – Argparse, Docopt, and Click

 

Build Command-Line Interfaces With Python's argparse – Real Python

In this step-by-step Python tutorial, you'll learn how to take your command-line Python scripts to the next level by adding a convenient command-line interface (CLI) that you can write with the argparse module from the standard library.

realpython.com


 

728x90

'Programming' 카테고리의 다른 글

[Python] recursive call : Fibonacci Sequence (and dynamic programming)  (0) 2023.05.24
[ML] Levenshtein distance  (1) 2023.05.17
[NumPy] searchsorted  (0) 2023.03.29
[Basic] Literal  (0) 2023.02.20
[Programming] Primitive Data Type : C, C++, NumPy, Torch  (0) 2023.02.01
'Programming' 카테고리의 다른 글
  • [Python] recursive call : Fibonacci Sequence (and dynamic programming)
  • [ML] Levenshtein distance
  • [NumPy] searchsorted
  • [Basic] Literal
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (785)
      • Private Life (15)
      • Programming (55)
        • DIP (116)
        • ML (34)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (368)
        • Signals and Systems (115)
        • Math (176)
        • Linear Algebra (33)
        • Physics (43)
        • 인성세미나 (1)
      • 정리필요. (61)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (7)
        • PET Study 2009 (1)
        • 방사선 장해방호 (5)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    function
    random
    signals_and_systems
    Python
    fourier transform
    인허가제도
    SIGNAL
    Vector
    ML
    opencv
    SS
    cv2
    linear algebra
    math
    Optimization
    Term
    Probability
    Programming
    signal_and_system
    numpy
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
[Python] argparse 모듈 사용하기.
상단으로

티스토리툴바