Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want Python argparse to throw an exception rather than usage

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.

like image 761
joedborg Avatar asked Feb 06 '13 11:02

joedborg


People also ask

Why use argument in exceptions in Python?

Why use Argument in Exceptions? It can be used to gain additional information about the error encountered. As contents of an Argument can vary depending upon different types of Exceptions in Python, Variables can be supplied to the Exceptions to capture the essence of the encountered errors.

How do I throw an exception in Python?

The raised exception typically warns the user or the calling application. You use the “raise” keyword to throw a Python exception manually. You can also add a message to describe the exception Here is a simple example: Say you want the user to enter a date.

What is argparse in Python?

Python's standard library module for interpreting command-line arguments, argparse, supplies a host of features, making it easy to add argument handling to scripts in a fashion that is consistent with other tools.

What is argumenttypeerror in argparse?

raise argparse.ArgumentTypeError ('invalid value!!!') If the argument passed is not in the given range, for example, the argument given for the first time the image above ‘ 3 ‘, the error message invalid value!!! is displayed. The argument passed next time is 10 which is in the specified range and thus the square of 10 is printed.


2 Answers

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(...) ... 
like image 100
Ned Batchelder Avatar answered Sep 25 '22 23:09

Ned Batchelder


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 
like image 33
Jacob CUI Avatar answered Sep 25 '22 23:09

Jacob CUI