到目前为止我有这个代码:
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()
为游戏数量提供负值是没有意义的,但是type=int
允许任何整数。例如,如果我运行python simulate_many.py -g -2
, args.games
将被设置为-2
并且程序将继续运行,就好像没有任何问题一样。
我意识到我可以明确检查args.games
解析参数后。但我可以做吗argparse
自己检查这个条件吗?如何?
我希望它以这种方式工作,以便自动使用消息可以向用户解释需求。理想情况下,输出将类似于:
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'
就像它当前处理无法转换为整数的参数一样:
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'
这应该可以利用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
函数在docs on argparse
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)