IT

Python에서는 argparse를 사용하여 양의 정수만 허용하십시오.

lottoking 2020. 6. 29. 07:37
반응형

Python에서는 argparse를 사용하여 양의 정수만 허용하십시오.


제목은 내가하고 싶은 것을 요약합니다.

여기 내가 가진 것이 있으며 프로그램이 양수가 아닌 정수를 폭파 시키지는 않지만, 양수가 아닌 정수는 기본적으로 말도 안된다는 정보를 사용자에게 알기를 원합니다.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-g", "--games", type=int, default=162,
                    help="The number of games to simulate")
args = parser.parse_args()

그리고 출력 :

python simulate_many.py -g 20
Setting up...
Playing games...
....................

네거티브 출력 :

python simulate_many.py -g -2
Setting up...
Playing games...

이제는 if args.games부정적인 판단을 위해 if를 추가 할 수 는 있지만 argparse자동 사용량 인쇄를 활용하기 위해 레벨 에서 트랩 을 잡을 방법이 있는지 궁금합니다 .

이상적으로는 다음과 비슷한 것을 인쇄합니다.

python simulate_many.py -g a
usage: simulate_many.py [-h] [-g GAMES] [-d] [-l LEAGUE]
simulate_many.py: error: argument -g/--games: invalid int value: 'a'

이렇게 :

python simulate_many.py -g -2
usage: simulate_many.py [-h] [-g GAMES] [-d] [-l LEAGUE]
simulate_many.py: error: argument -g/--games: invalid positive int value: '-2'

지금 나는 이것을하고 있으며, 나는 행복하다고 생각합니다.

if args.games <= 0:
    parser.print_help()
    print "-g/--games: must be positive."
    sys.exit(1)

이를 활용하여 가능해야합니다 type. 여전히이를 결정하는 실제 방법을 정의해야합니다.

def check_positive(value):
    ivalue = int(value)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value)
    return ivalue

parser = argparse.ArgumentParser(...)
parser.add_argument('foo', type=check_positive)

이것은 기본적으로 perfect_square에 대한 문서기능을 개조 한 예 입니다 argparse.


type Yuushi의 답변과 같이 조건 / 검사를 처리하는 데 권장되는 옵션입니다.

특정한 경우 choices상한도 알려진 경우 매개 변수를 사용할 수도 있습니다.

parser.add_argument('foo', type=int, choices=xrange(5, 10))

예측 가능한 최대 값과 인수에 대한 최소값이 있으면 빠르고 더러운 방법 choices은 범위와 함께 사용 하는 것입니다.

parser.add_argument('foo', type=int, choices=xrange(0, 1000))

더 간단한 대안은, 특히 서브 클래 싱 argparse.ArgumentParser경우 parse_args메소드 내부에서 유효성 검증을 시작하는 것입니다.

이러한 서브 클래스 내부 :

def parse_args(self, args=None, namespace=None):
    """Parse and validate args."""
    namespace = super().parse_args(args, namespace)
    if namespace.games <= 0:
         raise self.error('The number of games must be a positive integer.')
    return namespace

이 기술은 커스텀 콜 러블만큼 멋지지는 않지만 일을합니다.


소개 ArgumentParser.error(message):

이 메소드는 메시지를 포함하는 사용법 메시지를 표준 오류로 인쇄하고 상태 코드 2로 프로그램을 종료합니다.


Credit: answer by jonatan

참고URL : https://stackoverflow.com/questions/14117415/in-python-using-argparse-allow-only-positive-integers

반응형