티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
In Python, using argparse, allow only positive integers
Python에서 argparse로 양의 정수만 허용하기
문제 내용
The title pretty much summarizes what I'd like to have happen.
제목은 제가 하고 싶은 일을 거의 요약하고 있습니다.
Here is what I have, and while the program doesn't blow up on a nonpositive integer, I want the user to be informed that a nonpositive integer is basically nonsense.
여기 제가 가지고 있는 것이 있습니다. 프로그램이 양이 아닌 정수로 폭발하지는 않지만, 저는 사용자에게 양이 아닌 정수가 기본적으로 넌센스라는 것을 알려주고 싶습니다.
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()
And the output:
출력은 다음과 같습니다.
python simulate_many.py -g 20
Setting up...
Playing games...
....................
Output with a negative:
음의 출력:
python simulate_many.py -g -2
Setting up...
Playing games...
Now, obviously I could just add an if to determine if args.games
is negative, but I was curious if there was a way to trap it at the argparse
level, so as to take advantage of the automatic usage printing.
물론 args.games가 부정적인지 확인하기 위해 if를 추가할 수 있지만, 자동 사용 인쇄를 활용하기 위해 argparse 수준에서 이를 트랩할 수 있는 방법이 있는지 궁금했습니다.
Ideally, it would print something similar to this:
이상적으로는 다음과 유사한 내용을 인쇄합니다.
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'
Like so:
이와 같이:
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'
For now I'm doing this, and I guess I'm happy:
지금은 내가 이걸 하고 있고, 난 행복하다고 생각해.
if args.games <= 0:
parser.print_help()
print "-g/--games: must be positive."
sys.exit(1)
높은 점수를 받은 Solution
This should be possible utilizing type
. You'll still need to define an actual method that decides this for you:
이것은 유형을 이용하여 가능해야 한다. 이를 결정하는 실제 방법을 정의해야 합니다.
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)
This is basically just an adapted example from the perfect_square
function in the docs on argparse
.
이것은 기본적으로 argparse의 문서에 있는 perfect_square 함수의 적용된 예에 불과합니다.
가장 최근 달린 Solution
Based on Yuushi's answer, you can also define a simple helper function that can check if a number is positive for various numeric types:
유우시의 답변을 기반으로 다양한 숫자 유형에 대해 숫자가 양수인지 확인할 수 있는 간단한 도우미 기능도 정의할 수 있습니다.
def positive(numeric_type):
def require_positive(value):
number = numeric_type(value)
if number <= 0:
raise ArgumentTypeError(f"Number {value} must be positive.")
return number
return require_positive
The helper function can be used to annotate any numeric argument type like this:
헬퍼 함수를 사용하여 다음과 같이 숫자 인수 유형에 주석을 달 수 있습니다.
parser = argparse.ArgumentParser(...)
parser.add_argument("positive-integer", type=positive(int))
parser.add_argument("positive-float", type=positive(float))
출처 : https://stackoverflow.com/questions/14117415/in-python-using-argparse-allow-only-positive-integers
'개발 > 파이썬' 카테고리의 다른 글
비어 있지 않은 폴더 삭제하기 (0) | 2022.12.06 |
---|---|
파이썬에서 파일 크기 확인하기 (0) | 2022.12.05 |
딕셔너리 키값 기준으로 정렬하기 (0) | 2022.12.05 |
type object 'datetime.datetime' has no attribute 'datetime' 오류 수정하기 (0) | 2022.12.05 |
ImportError: numpy.core.multiarray failed to import 수정하기 (0) | 2022.12.05 |