标题几乎概括了我希望发生的事情。
这就是我所拥有的,虽然程序不会在非正整数上崩溃,但我希望用户被告知非正整数基本上是无稽之谈。
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
处捕获它级别,以便利用自动使用打印。
理想情况下,它会打印类似这样的内容:
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)
这基本上只是 docs 中 perfect_square
函数的改编示例在 argparse
上。
https://stackoverflow.com/questions/14117415/