Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I require my python script's argument to be a float between 0.0-1.0 using argparse?

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?

like image 981
Dolan Antenucci Avatar asked Aug 24 '12 21:08

Dolan Antenucci


People also ask

How do you add an optional argument in Argparse?

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.

What is Store_true in Python?

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.

What does parse_args return?

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.


1 Answers

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) 
like image 182
chepner Avatar answered Oct 09 '22 07:10

chepner