我有以下代码尝试从调用的命令行获取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'.
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)