Python argparse fails to parse hex formatting to int type

馋奶兔 提交于 2019-12-21 03:17:41

问题


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

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?


回答1:


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

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')

Note the type is update to be 'auto_int'.




回答2:


Not enough reputation to comment on the other answer.

If you don't want to define the auto_int function, I found that this works very cleanly with a lambda.

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


来源:https://stackoverflow.com/questions/25513043/python-argparse-fails-to-parse-hex-formatting-to-int-type

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