How to reject negative numbers as parameters in Argparse module

I have a time parameter, and it can be any number, except negative and zero

parser.add_argument("-t", "--time",
                    default=2, type=int,
                    help="Settings up the resolution time")

How to use the selection option?

+4
source share
1 answer

You can pass any conversion function as type=arg add_argument. Use your own conversion function, which includes additional checks.

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")
+5
source

Source: https://habr.com/ru/post/1674386/


All Articles