如何拒绝负数作为 Argparse 模块中的参数
How to reject negative numbers as parameters in the Argparse module
我有一个时间参数,它可以是除负数和零以外的任何数字
parser.add_argument("-t", "--time",
default=2, type=int,
help="Settings up the resolution time")
如何正确使用选择选项?
您可以将任何转换函数作为 add_argument
的 type=
arg 传递。使用您自己的转换函数,其中包括额外的检查。
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")
我有一个时间参数,它可以是除负数和零以外的任何数字
parser.add_argument("-t", "--time",
default=2, type=int,
help="Settings up the resolution time")
如何正确使用选择选项?
您可以将任何转换函数作为 add_argument
的 type=
arg 传递。使用您自己的转换函数,其中包括额外的检查。
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")