10
votes

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!

5
I don't think it's possible. But you can use hex to make the formatting more readable. - user395760

5 Answers

22
votes

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.

4
votes

Building on previous answers, here's a version that works for Python 2/3, doesn't display bools as hex, and also properly sets the _ variable:

import sys

def _displayhook(o):
    if type(o).__name__ in ('int', 'long'):
        print(hex(o))
        __builtins__._ = o
    else:
        sys.__displayhook__(o)

def hexon():
    sys.displayhook = _displayhook
def hexoff():
    sys.displayhook=sys.__displayhook__
3
votes

Something like this, perhaps?

class HexInt(int):
    "Same as int, but __repr__() uses hex"

    def __repr__(self):
        return hex(self)

So you'd use that when creating all your integers that you want to be shown as hex values.

Example:

>>> a = HexInt(12345)
>>> b = HexInt(54321)
>>> a
0x3039
>>> b
0xd431
>>> c = HexInt(a + b)
>>> c
0x1046a

Note that if you wanted to skip the explicit creation of a new HexInt when doing arithmetic operations, you'd have to override the existing int versions of methods such as __add__(), __sub__(), etc., such that they'd return HexInts.

3
votes

Modifying the top python2 answer for python3...

def display_as_hex(item):
    if isinstance(item, int):
        print(hex(item))
    else:
        print(repr(item))
import sys
sys.displayhook = display_as_hex
0
votes

You could so something like this:

while True:
  print hex(input('> '))

To get a basic prompt that prints the hex value of all of the results. You could even make it conditional -- check to see if the return type of input is a string or number, and if it is, print the hex value, else print the value normally.