I want Python argparse to throw an exception rather than usage
You can subclass ArgumentParser
and override the error
method to do something different when an error occurs:
class ArgumentParserError(Exception): pass
class ThrowingArgumentParser(argparse.ArgumentParser):
def error(self, message):
raise ArgumentParserError(message)
parser = ThrowingArgumentParser()
parser.add_argument(...)
...
in my case, argparse prints 'too few arguments' then quit. after reading the argparse code, I found it simply calls sys.exit() after printing some message. as sys.exit() does nothing but throws a SystemExit exception, you can just capture this exception.
so try this to see if it works for you.
try:
args = parser.parse_args(args)
except SystemExit:
.... your handler here ...
return