【问题标题】:How to override ipython displayhook?如何覆盖 ipython 显示挂钩?
【发布时间】:2016-03-10 10:06:57
【问题描述】:

我定义了自己的 displayhook,它继承自 IPython.core.displayhook.DisplayHook。

关于覆盖 IPython shell 的显示挂钩的正确方法,我无法在线找到任何资源。目前,我在 ~/.ipython/profile_default/startup/imports.py 中执行以下操作:

ipyShell = IPython.get_ipython()
ipyShell.displayhook = MyDisplayHook(shell=ipyShell)
ipyShell.displayhook_class = MyDisplayHook
sys.displayhook = ipyShell.displayhook

这不起作用,因为在 ipython shell 启动后,sys.displayhook 会以某种方式切换回常规的 ipython 显示挂钩:

In [5]: print sys.displayhook
<IPython.core.displayhook.DisplayHook object at 0x7f1491853610>

谢谢。

【问题讨论】:

    标签: python ipython


    【解决方案1】:

    如果有人偶然发现这一点(就像我一样),与标准的 python 显示挂钩相比,格式化 IPython 的方式乍一看实际上可能会产生误导。

    在这个答案中,我尝试首先详细说明 IPython 的不同部分以澄清,然后在最后解决 OP(和我的)的具体问题。

    在 IPython 中,您可以自定义几乎所有内容,仅使用与标准 python displayhook 相差甚远的方法。

    IPython 中所谓的“钩子”(参见 docthis example)实际上是旨在改变 shell 行为的东西。

    或者可以更改编辑器的外观,即

    In [5]: def foo():
       ...:     return 'foo'
       ...:
    

    接口,特别是In [5]:...: 部分。 为此,您可以查看 IPython doc 以了解如何使用 Prompts 执行此操作。

    最终,为了改变 python 对象的输出格式,我不得不使用 IPython formatters(参见source code)和 pretty printing 函数定义here

    例如,如果您想更改默认的dict 格式

    {'axon_angle': 305.010625458 degree,
     'observables': ['length',
       'num_growth_cones'],
     'random_rotation_angles': True}
    

    {
      'axon_angle'            : 305.010625458 degree,
      'observables'           : [
        'length',
        'num_growth_cones',
      ],
      'random_rotation_angles': True
    }
    

    你可以使用类似的东西

    def dict_formatter(obj, p, cycle):
        if cycle:
            return p.text('{...}')
        start = '{'
        end   = '}'
        step = 2
        p.begin_group(step, start)
        keys = obj.keys()
        max_len = 0
        for k, v in obj.items():
            max_len = max(max_len, len(str(k)))
    
        if obj:
            p.breakable()
        for idx, key in p._enumerate(keys):
            if idx:
                p.text(',')
                p.breakable()
            p.pretty(key)
            wlen = max_len-len(str(key))
            p.text(' '*wlen + ': ')
            p.pretty(obj[key])
        if obj:
            p.end_group(step, '')
            p.breakable()
            p.text(end)
        else:
            p.end_group(step, end)
    
    import IPython
    ip = IPython.get_ipython()
    formatter = ip.display_formatter.formatters['text/plain']
    formatter.for_type(dict, dict_formatter)
    

    【讨论】:

      猜你喜欢
      • 2016-10-29
      • 1970-01-01
      • 2018-10-09
      • 2011-02-08
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多