【问题标题】:How can I configure ipython to display integers in hex format?如何配置 ipython 以十六进制格式显示整数?
【发布时间】:2013-02-05 06:57:24
【问题描述】:

这是默认行为:

In [21]: 255
Out[21]: 255

这就是我想要的:

In [21]: 255
Out[21]: FF

我可以设置 ipython 来做到这一点吗?

【问题讨论】:

标签: python ipython


【解决方案1】:

您可以通过为整数注册一个特殊的显示格式化程序来做到这一点:

In [1]: formatter = get_ipython().display_formatter.formatters['text/plain']

In [2]: formatter.for_type(int, lambda n, p, cycle: p.text("%X" % n))
Out[2]: <function IPython.lib.pretty._repr_pprint>

In [3]: 1
Out[3]: 1

In [4]: 100
Out[4]: 64

In [5]: 255
Out[5]: FF

如果你想要这个永远在线,你可以在$(ipython locate profile)/startup/hexints.py 中创建一个文件,前两行(或作为一个以避免任何分配):

get_ipython().display_formatter.formatters['text/plain'].for_type(int, lambda n, p, cycle: p.text("%X" % n))

每次启动 IPython 时都会执行。

【讨论】:

  • 完美。正是我想要的。非常感谢!
  • 更好:打印两种表示形式! formatter.for_type(int, lambda n, p, cycle: p.text("%d (0x%X)" % (n,n)))
  • 这个建议太棒了,将节省我输入hex(...) 的累积小时数以获取十六进制格式的结果。
  • cycle 在 lambda 定义中做了什么?
  • 我尝试删除cycle,出现错误,并查看了相关源代码。在这种情况下似乎无关紧要,但与打印可迭代对象有关。
【解决方案2】:

基于minrk's answerrjb's answer 的另一个问题,我把它放在我的Python 启动文件中:

def hexon_ipython():
  '''To print ints as hex, run hexon_ipython().
  To revert, run hexoff_ipython().
  '''
  formatter = get_ipython().display_formatter.formatters['text/plain']
  formatter.for_type(int, lambda n, p, cycle: p.text("0x%x" % n))


def hexoff_ipython():
  '''See documentation for hexon_ipython().'''
  formatter = get_ipython().display_formatter.formatters['text/plain']
  formatter.for_type(int, lambda n, p, cycle: p.text("%d" % n))


hexon = hexon_ipython
hexoff = hexoff_ipython

所以我可以这样使用它:

In [1]: 15
Out[1]: 15

In [2]: hexon()

In [3]: 15
Out[3]: 0xf

In [4]: hexoff()

In [5]: 15
Out[5]: 15

【讨论】:

    猜你喜欢
    • 2021-09-18
    • 1970-01-01
    • 2011-02-18
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 2011-03-22
    相关资源
    最近更新 更多