我有一个时间参数,它可以是除负数和零以外的任何数字
parser.add_argument("-t", "--time",
default=2, type=int,
help="Settings up the resolution time")
如何正确使用选择选项?
最佳答案
您可以将任何转换函数作为 type=
add_argument
的参数.使用您自己的转换功能,其中包括额外的检查。
def non_negative_int(x):
i = int(x)
if i < 0:
raise ValueError('Negative values are not allowed')
return i
parser.add_argument("-t", "--time",
default=2, type=non_negative_int,
help="Settings up the resolution time")
关于python-3.x - 如何拒绝负数作为 Argparse 模块中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43299736/