50

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.

3
  • 5
    Actually you can already do that. simply catch SystemExit and replace sys.stderr with some other object. Commented Feb 6, 2013 at 12:01
  • 1
    Depending on what you want to do, it may be better to modify the argument itself. Is the argument to --foo optional? Can you define a custom action to handle it? These may be cleaner actions than overriding argparse's decision to exit. Commented Feb 6, 2013 at 13:01
  • Python 3.9 added a exit_on_error parameter to ArgumentParser(), but it does not (yet?) throw an error for a missing required option nor an unrecognized option. See bugs.python.org/issue41255. Commented Oct 26, 2021 at 23:50

2 Answers 2

83

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(...) ... 
Sign up to request clarification or add additional context in comments.

1 Comment

I was hoping to avoid something like this, though I'm glad it's an option. You see, I'm trying to print out the help menu when I get an "error: too few arguments" notification; my argparse setup requires at least one argument to run successfully, but I figure it'd be polite to print out what those commands are without the user having to run the script with the "-h" parameter. Something like: parser.set_error('too few arguments', method_to_deal_with_error) I suppose I can always file a bug if I want this feature. Thanks!
27

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 

2 Comments

Yes, this option is mentioned above in Bakuriu's comment. The unittesting test_argparse.py file uses this approach, along with redefining error to create a ErrorRaisingArgumentParser class.
@Raj You can temporarily redirect stderr to another stream/file object, for example: stackoverflow.com/a/6796752/2128769

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.