本文介绍了Python argparse无法将十六进制格式解析为int类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码尝试从调用的命令行获取DUT VID:

I have the following code which attempts to get the DUT VID from the invoked command line:

parser = argparse.ArgumentParser(description='A Test',
                                 formatter_class=argparse.ArgumentDefaultsHelpFormatter
                                 )
group.add_argument("--vid",
                   type=int,
                   help="vid of DUT")
options = parser.parse_args()

考虑命令行"python test.py --vid 0xabcd"我注意到argparse在此引发异常,因为它无法完成调用int('0xabcd'),因为它是基于16的.我如何使argparse正确处理此问题?

Consider the command line "python test.py --vid 0xabcd"I notice that argparse is raising an exception on this as it fails to complete the call int('0xabcd') because it is base 16. How do I get argparse to correctly handle this?

推荐答案

argparse希望从'type'值创建可调用的类型转换:

argparse is looking to create a callable type conversion from the 'type' value:

    def _get_value(self, action, arg_string):
        type_func = self._registry_get('type', action.type, action.type)
        if not _callable(type_func):
            msg = _('%r is not callable')
            raise ArgumentError(action, msg % type_func)

        # convert the value to the appropriate type
        try:
            result = type_func(arg_string)

        # ArgumentTypeErrors indicate errors
        except ArgumentTypeError:
            name = getattr(action.type, '__name__', repr(action.type))
            msg = str(_sys.exc_info()[1])
            raise ArgumentError(action, msg)

        # TypeErrors or ValueErrors also indicate errors
        except (TypeError, ValueError):
            name = getattr(action.type, '__name__', repr(action.type))
            msg = _('invalid %s value: %r')
            raise ArgumentError(action, msg % (name, arg_string))

        # return the converted value
        return result

默认情况下,int()设置为以10为底.为了适应以16和10为底的参数,我们可以启用自动碱基检测:

By default int() is set to base 10. In order to accommodate base 16 and base 10 parameters we can enable auto base detection:

    def auto_int(x):
        return int(x, 0)
    ...
    group.add_argument('--vid',
                       type=auto_int,
                       help='vid of DUT')

请注意类型已更新为'auto_int'.

这篇关于Python argparse无法将十六进制格式解析为int类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 17:59