简体   繁体   中英

How to reject negative numbers as parameters in the Argparse module

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

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

How can I use choices option correctly?

You can pass any conversion function as the type= arg of add_argument . Use your own converstion function, which includes the extra 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM