I'd like to use argparse on Python 2.7 to require that one of my script's parameters be between the range of 0.0 and 1.0.  Does argparse.add_argument() support this?
Optional arguments are useful if you want to give the user a choice to enable certain features. To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.
Adding arguments Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.
The type parameter to add_argument just needs to be a callable object that takes a string and returns a converted value. You can write a wrapper around float that checks its value and raises an error if it is out of range.
def restricted_float(x):     try:         x = float(x)     except ValueError:         raise argparse.ArgumentTypeError("%r not a floating-point literal" % (x,))      if x < 0.0 or x > 1.0:         raise argparse.ArgumentTypeError("%r not in range [0.0, 1.0]"%(x,))     return x  p = argparse.ArgumentParser() p.add_argument("--arg", type=restricted_float) 
                        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