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?
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.
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.
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+)?$')
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With