Search code examples
pythonread-eval-print-loop

Python console default hex display


I'm doing a bunch of work in the Python console, and most of it is referring to addresses, which I'd prefer to see in hex.

So if a = 0xBADF00D, when I simply enter Python> a into the console to view its value, I'd prefer python to reply with 0xBADF00D instead of 195948557.

I know I can enter '0x%X' % a to see it in hex, but I'm looking for some sort of python console option to have it do this automatically. Does something liket this exist? Thanks!


Solution

  • The regular Python interpreter will call sys.displayhook to do the actual displaying of expressions you enter. You can replace it with something that displays exactly what you want, but you have to keep in mind that it is called for all expressions the interactive interpreter wants to display:

    >>> import sys
    >>> 1
    1
    >>> "1"
    '1'
    >>> def display_as_hex(item):
    ...     if isinstance(item, (int, long)):
    ...         print hex(item)
    ...     else:
    ...         print repr(item)
    ...
    >>> sys.displayhook = display_as_hex
    >>> 1
    0x1
    >>> "1"
    '1'
    

    I suspect you'll quickly get tired of seeing all integers as hex, though, and switch to explicitly converting the ones you want to see as hex accordingly.