Python argparse无法将十六进制格式解析为int类型

dev*_*anl 20 python argparse

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

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

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

dev*_*anl 31

argparse正在寻找从'type'值创建可调用类型转换:

    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
Run Code Online (Sandbox Code Playgroud)

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

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

请注意,类型是更新'auto_int'.

  • 正如其变体一样,“type=functools.partial(int, base=0)”无需明确的 Python 级别函数定义(没有“def”、没有“lambda”)即可工作。 (2认同)

Jos*_*yan 13

没有足够的声誉评论其他答案.

如果您不想定义该auto_int函数,我发现这与lambda非常干净.

group.add_argument('--vid',
                   type=lambda x: int(x,0),
                   help='vid of DUT')
Run Code Online (Sandbox Code Playgroud)

  • 当您使用 lambda 时,argparse 打印的错误消息将显示“无效的 <lambda> 值”,而不是“无效的 auto_int 值”。 (3认同)
  • 您可以执行 `functools.wraps(int)(lambda x: int(x,0))` 或 `functools.wraps(int)(functools.partial(int, base=0))` ,然后错误消息将引用`无效的 int 值`。 (3认同)
  • @devanl [Python 从 1.0 开始就支持 lambdas](https://en.wikipedia.org/wiki/History_of_Python#Version_1) 。 (2认同)