Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse fails to parse hex formatting to int type

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?

like image 250
devanl Avatar asked Aug 31 '25 15:08

devanl


2 Answers

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

like image 159
devanl Avatar answered Sep 02 '25 12:09

devanl


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')
like image 20
Joshua Ryan Avatar answered Sep 02 '25 14:09

Joshua Ryan