Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python argparse의 nargs 옵션으로 동일한 유형의 위치 인수 두 개 처리하기

소개

두 숫자에 대해 산술 연산을 수행하는 프로그램을 작성한다고 가정해 봅시다. 이 경우 일반적으로 두 개의 위치 인수(positional argument)를 정의하게 됩니다. 그런데 두 인수가 같은 종류, 즉 동일한 Python 데이터 타입이라면 argparse의 nargs 옵션을 사용해 "정확히 같은 타입의 값 두 개"를 받도록 지정하는 것이 더 깔끔하고 직관적인 방법입니다.

구현 방법

nargs 옵션을 활용하여 두 숫자의 뺄셈을 수행하는 프로그램을 작성해 보겠습니다.

import argparse

def get_args():
    """ Function : get_args
    parameters used in .add_argument
    1. metavar - Provide a hint to the user about the data type.
       - By default, all arguments are strings.

    2. type - The actual Python data type
       - (note the lack of quotes around str)

    3. help - A brief description of the parameter for the usage

    4. nargs - require exactly nargs values.
    """

    parser = argparse.ArgumentParser(
        description='Example for nargs',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('numbers',
                        metavar='int',
                        nargs=2,
                        type=int,
                        help='Numbers of type int for subtraction')

    return parser.parse_args()

def main():
    args = get_args()
    num1, num2 = args.numbers
    print(f" *** Subtracting two number - {num1} - {num2} = {num1 - num2}")

if __name__ == '__main__':
    main()

주요 포인트

  • nargs=2 : 정확히 두 개의 값을 요구합니다.

  • type=int : 각 값은 반드시 정수여야 하며, 그렇지 않으면 프로그램이 오류를 발생시킵니다.

  • 인수의 개수가 맞지 않거나 잘못된 타입의 값이 전달되면 argparse가 자동으로 사용법(usage) 메시지와 함께 오류를 출력합니다.

실행 결과

다양한 값을 전달하며 프로그램을 실행해 보겠습니다.

$ python test.py 30 10
*** Subtracting two number - 30 - 10 = 20

$ python test.py 10 30
*** Subtracting two number - 10 - 30 = -20

$ python test.py 10 10 30
usage: test.py [-h] int int
test.py: error: unrecognized arguments: 30

$ python test.py
usage: test.py [-h] int int
test.py: error: the following arguments are required: int

추가로 알아두면 좋은 nargs 값들

nargs에는 숫자 외에도 다양한 값을 지정할 수 있습니다.

  • nargs='?' : 0개 또는 1개의 인수를 허용합니다.

  • nargs='*' : 0개 이상의 모든 인수를 리스트 형태로 수집합니다.

  • nargs='+' : 1개 이상의 인수를 요구하며, 값이 없으면 오류를 발생시킵니다.

이처럼 nargs 옵션을 활용하면 동일한 타입의 위치 인수를 손쉽게 처리할 수 있어, 명령줄 인터페이스(CLI) 프로그램을 작성할 때 코드의 가독성과 입력값 검증의 안정성이 크게 향상됩니다.