I want Python argparse to throw an exception rather than usage

[亡魂溺海] 提交于 2019-12-17 22:36:34

问题


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.


回答1:


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(...)
...



回答2:


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


来源:https://stackoverflow.com/questions/14728376/i-want-python-argparse-to-throw-an-exception-rather-than-usage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!