在Python中,使用argparse,仅允许使用正整数 [英] In Python, using argparse, allow only positive integers
问题描述
标题几乎总结了我想发生的事情.
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()
输出:
python simulate_many.py -g 20
Setting up...
Playing games...
....................
输出为负:
python simulate_many.py -g -2
Setting up...
Playing games...
现在,显然我可以添加一个if来确定if args.games
是否为负,但是我很好奇是否有一种方法可以将其捕获在argparse
级别,以便利用自动用法打印.
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.
理想情况下,它将打印类似以下内容的内容:
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'
像这样:
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)
推荐答案
使用type
应该可以实现.您仍然需要定义一个实际的方法来为您决定:
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)
这基本上只是 docs 中perfect_square
函数的改编示例argparse
上的a>.
This is basically just an adapted example from the perfect_square
function in the docs on argparse
.
这篇关于在Python中,使用argparse,仅允许使用正整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!