I\'d like to use the ArgumentError
exception in the argparse
module in Python, but I can\'t figure out how to use it. The signature says that it sh
While parser.error()
is what most people probably want, it is also possible to use argparse.ArgumentError() (as the question asks.) You need a reference to the argument, like the bar_arg
in the example below:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo')
bar_arg = parser.add_argument('--bar')
args = parser.parse_args()
if args.bar == 'xyzzy':
raise argparse.ArgumentError(bar_arg, "Can't be 'xyzzy'")
if args.foo == 'xyzzy':
parser.error("Can't be 'xyzzy'")
This will result in output like the one below:
$ python argparse_test.py --foo xyzzy
usage: argparse_test.py [-h] [--foo FOO] [--bar BAR]
argparse_test.py: error: Can't be 'xyzzy'
$ python argparse_test.py --bar xyzzy
Traceback (most recent call last):
File "argparse_test.py", line 10, in
raise argparse.ArgumentError(bar_arg, "Can't be 'xyzzy'")
argparse.ArgumentError: argument --bar: Can't be 'xyzzy'