Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 733
pala9323 Avatar asked Apr 08 '17 19:04

pala9323


People also ask

What is the argparse module in Python?

The argparse module also automatically generates help and usage messages, and issues errors when users give the program invalid arguments. The argparse is a standard module; we do not need to install it. A parser is created with ArgumentParser and a new parameter is added with add_argument. Arguments can be optional, required, or positional.

How do I pass a function to an argument in argparse?

The argparse module has a function called add_arguments () where the type to which the argument should be converted is given. Instead of using the available values, a user-defined function can be passed as a value to this parameter.

How to use negative number matcher in argparse?

Another workaround is to pass in the argument using ' = ' symbol in addition to quoting the argument - i.e., --xlim="-2.3e14" If you are up to modifying argparse.py itself, you could change the negative number matcher to handle scientific notation: self._negative_number_matcher = _re.compile (r'^- (\d+\.?|\d*\.\d+) ( [eE] [+\-]?\d+)?$')

What is argumenttypeerror in argparse?

raise argparse.ArgumentTypeError ('invalid value!!!') If the argument passed is not in the given range, for example, the argument given for the first time the image above ‘ 3 ‘, the error message invalid value!!! is displayed. The argument passed next time is 10 which is in the specified range and thus the square of 10 is printed.


1 Answers

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")
like image 122
shx2 Avatar answered Nov 07 '22 01:11

shx2