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?
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'
.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With