Python控制台默认十六进制显示
我在 Python 控制台中做了很多工作,其中大部分都涉及地址,我更喜欢以十六进制形式查看地址。
因此,如果a = 0xBADF00D
,当我只需输入Python>时; a
进入控制台查看其值,我更喜欢 python 回复 0xBADF00D
而不是 195948557
。
我知道我可以输入 '0x%X' % a
以十六进制形式查看它,但我正在寻找某种 python 控制台选项以使其自动执行此操作。存在这样的东西吗?谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
常规 Python 解释器将调用 sys.displayhook 来实际显示您输入的表达式。您可以将其替换为能够准确显示您想要的内容的内容,但您必须记住,它是为交互式解释器想要显示的所有表达式而调用的:
我怀疑您很快就会厌倦不过,将所有整数视为十六进制,并相应地切换到显式转换您想要查看的整数。
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: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.
基于之前的答案,这里有一个适用于 Python 2/3 的版本,不将布尔值显示为十六进制,并且还正确设置了
_
变量: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:也许是这样的?
因此,您可以在创建要显示为十六进制值的所有整数时使用它。
示例:
请注意,如果您想在进行算术运算时跳过显式创建新的
HexInt
,则必须重写方法的现有int
版本,例如 < code>__add__()、__sub__()
等,这样它们就会返回HexInt
。Something like this, perhaps?
So you'd use that when creating all your integers that you want to be shown as hex values.
Example:
Note that if you wanted to skip the explicit creation of a new
HexInt
when doing arithmetic operations, you'd have to override the existingint
versions of methods such as__add__()
,__sub__()
, etc., such that they'd returnHexInt
s.修改 python3 的顶级 python2 答案...
Modifying the top python2 answer for python3...
您可以这样做:
获得打印所有结果的十六进制值的基本提示。您甚至可以将其设置为有条件的 - 检查输入的返回类型是否是字符串或数字,如果是,则打印十六进制值,否则正常打印该值。
You could so something like this:
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.