I don't think this is possible, but I want to handle exceptions from argparse myself.
For example:
import argparse parser = argparse.ArgumentParser() parser.add_argument('--foo', help='foo help', required=True) try: args = parser.parse_args() except: do_something() When I run it:
$ myapp.py usage: myapp --foo foo myapp: error: argument --foo is required But I want it to fall into the exception instead.
SystemExitand replacesys.stderrwith some other object.--foooptional? Can you define a custom action to handle it? These may be cleaner actions than overridingargparse's decision to exit.exit_on_errorparameter toArgumentParser(), but it does not (yet?) throw an error for a missing required option nor an unrecognized option. See bugs.python.org/issue41255.