[英]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. 我认为这是不可能的,但是我想处理argparse自己的异常。
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. 但是我希望它成为例外。
You can subclass ArgumentParser
and override the error
method to do something different when an error occurs: 您可以继承
ArgumentParser
子类,并覆盖error
方法以在发生错误时做一些不同的事情:
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. 就我而言,argparse打印“参数太少”然后退出。 after reading the argparse code, I found it simply calls sys.exit() after printing some message.
阅读argparse代码后,我发现它在打印一些消息后仅调用sys.exit()。 as sys.exit() does nothing but throws a SystemExit exception, you can just capture this exception.
由于sys.exit()除了抛出SystemExit异常外什么也不做,因此您可以捕获此异常。
so try this to see if it works for you. 因此,请尝试此操作以查看是否适合您。
try:
args = parser.parse_args(args)
except SystemExit:
.... your handler here ...
return
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.