Python Argparse Integer Condition (>=12)
Solution 1:
One way is to use a custom type.
defbandwidth_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.
classBandwidthAction(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")
Solution 2:
You can call the parser error without creating custom types or separate functions. A simple change to your code example is enough:
import 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:
parser.error("Minimum bandwidth is 12")
This will cause the application to exit and display the parser error:
$ python test.py --bandwidth 11
usage: test.py [-h] [-b BANDWIDTH]
test.py: error: Minimum bandwidth is 12
Solution 3:
How about this?
import sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"-b", "--bandwidth",
type=lambda x: (int(x) > 11) andint(x) or sys.exit("Minimum bandwidth is 12"),
help="target bandwidth >=12"
)
But plese note, I didn't try it in a real code. Or you can change sys.exit
to parser.error
as wrote by @jonatan.
Post a Comment for "Python Argparse Integer Condition (>=12)"