本文介绍了Python argparse 和控制/覆盖退出状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了修改 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:

  • ArgumentError() 在 arg 解析失败时适当地引发.它传递参数实例和消息
  • ArgumentError() 确实将参数存储为实例属性,尽管被传递(这会很方便)
  • 可以通过子类化 ArgumentParser、覆盖 .error() 并从 sys.exc_info() 获取异常来重新引发 ArgumentError 异常
  • ArgumentError() is raised appropriately when arg parsing fails. It is passed the argument instance and a message
  • ArgumentError() 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 subclassing ArgumentParser, 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 和控制/覆盖退出状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 07:47