Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse integer condition (>=12)

I need to request that an argument is >= 12 using argparse.

I cannot find a way to obtain this result using argparse, it seems there's no way to set rules to a given value but only full sets of accepted values like choices=['rock', 'paper', 'scissors'].

My code is:

import sys, argparse  parser = argparse.ArgumentParser() parser.add_argument("-b", "--bandwidth", type=int, help="target bandwidth >=12") args = parser.parse_args() if args.bandwidth and args.bandwidth < 12:     print "ERROR: minimum bandwidth is 12"     sys.exit(1) 

I wonder if there is a way to obtain this result directly with some argparse option.

like image 225
giuspen Avatar asked Sep 09 '13 14:09

giuspen


People also ask

How do you add an optional argument in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What is Argumentparser in Python?

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv .

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. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.


1 Answers

One way is to use a custom type.

def bandwidth_type(x):     x = int(x)     if x < 12:         raise argparse.ArgumentTypeError("Minimum bandwidth is 12")     return x  parser.add_argument("-b", "--bandwidth", type=bandwidth_type, help="target bandwidth >= 12") 

Note: I think ArgumentTypeError is a more correct exception to raise than ArgumentError. However, ArgumentTypeError is not documented as a public class by argparse, and so it may not be considered correct to use in your own code. One option I like is to use argparse.error like alecxe does in his answer, although I would use a custom action instead of a type function to gain access to the parser object.

A more flexible option is a custom action, which provides access to the current parser and namespace object.

class BandwidthAction(argparse.Action):      def __call__(self, parser, namespace, values, option_string=None):         if values < 12:             parser.error("Minimum bandwidth for {0} is 12".format(option_string))             #raise argparse.ArgumentError("Minimum bandwidth is 12")          setattr(namespace, self.dest, values)  parser.add_argument("-b", "--bandwidth", action=BandwidthAction, type=int,                      help="target bandwidth >= 12") 
like image 168
chepner Avatar answered Oct 16 '22 17:10

chepner