问题描述
除了修补argparse
源之外,还有什么方法可以控制退出状态代码,当调用parse_args()
时是否应该有问题,例如缺少必需的开关?
Apart from tinkering with the argparse
source, is there any way to control the exit status code should there be a problem when parse_args()
is called, for example, a missing required switch?
推荐答案
我不知道有任何机制可以根据参数指定退出代码.您可以捕获在.parse_args()
上引发的SystemExit
异常,但是我不确定接下来如何确定是什么 引起了错误.
I'm not aware of any mechanism to specify an exit code on a per-argument basis. You can catch the SystemExit
exception raised on .parse_args()
but I'm not sure how you would then ascertain what specifically caused the error.
编辑:对于任何寻求实用解决方案的人,情况如下:
For anyone coming to this looking for a practical solution, the following is the situation:
- arg解析失败时,会适当引发
-
ArgumentError()
.它传递了参数实例和一条消息 -
ArgumentError()
不会不将参数存储为实例属性,尽管会被传递(这很方便) - 可以通过子类化
ArgumentParser
,重写.error()并从sys.exc_info()获取异常来重新引发ArgumentError
异常
ArgumentError()
is raised appropriately when arg parsing fails. It is passed the argument instance and a messageArgumentError()
does not store the argument as an instance attribute, despite being passed (which would be convenient)- It is possible to re-raise the
ArgumentError
exception by subclassingArgumentParser
, overriding .error() and getting hold of the exception from sys.exc_info()
这意味着下面的代码(虽然很丑陋)使我们能够捕获ArgumentError异常,掌握有问题的参数和错误消息,并按我们认为合适的方式进行操作:
All that means the following code - whilst ugly - allows us to catch the ArgumentError exception, get hold of the offending argument and error message, and do as we see fit:
import argparse
import sys
class ArgumentParser(argparse.ArgumentParser):
def _get_action_from_name(self, name):
"""Given a name, get the Action instance registered with this parser.
If only it were made available in the ArgumentError object. It is
passed as it's first arg...
"""
container = self._actions
if name is None:
return None
for action in container:
if '/'.join(action.option_strings) == name:
return action
elif action.metavar == name:
return action
elif action.dest == name:
return action
def error(self, message):
exc = sys.exc_info()[1]
if exc:
exc.argument = self._get_action_from_name(exc.argument_name)
raise exc
super(ArgumentParser, self).error(message)
## usage:
parser = ArgumentParser()
parser.add_argument('--foo', type=int)
try:
parser.parse_args(['--foo=d'])
except argparse.ArgumentError, exc:
print exc.message, '\n', exc.argument
未经任何有用的方式测试.通常,如果违反赔偿,不要怪我.
Not tested in any useful way. The usual don't-blame-me-if-it-breaks indemnity applies.
这篇关于Python argparse和控制/覆盖退出状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!