如何重写ipython displayhook? [英] How to override ipython displayhook?

查看:50
本文介绍了如何重写ipython 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 displayhook相比,格式化IPython的方式乍一看可能会产生误导. /p>

在这个答案中,我尝试首先详细说明IPython的不同部分,然后最后解决OP(和我的)的特定问题.

在IPython中,您只能使用与标准python displayhook相距甚远的方法自定义几乎所有内容.

在IPython中所谓的挂钩"(请参见文档 IPython文档查看如何使用Prompts进行操作.

最终,要更改python对象输出的格式,我不得不使用IPython formatters (请参阅 解决方案

In case someone stumbles on this (like I did), the way to format IPython can actually be misleading at first glance when compared to the standard python displayhook.

In this answer, I try to detail first the different parts of IPython to clarify, then tackle the specific question of the OP (and mine) at the end.

In IPython, you can customize almost everything, only using methods that are quite far from the standard python displayhook.

What is called "hooks" in IPython (see the doc and this example) is actually something aimed at altering the behavior of the shell.

Alternatively can change how the editor looks like, i.e. the

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

interface, and specifically the In [5]: and ...: parts. For that, you can have a look at the IPython doc to see how to do that with Prompts.

Eventually, to alter how the output of a python object is formatted, I had to use the IPython formatters (cf. source code) and the pretty printing functions defined here.

For instance, if you want to change the default dict formatting from

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

to

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

You can use something like

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)

这篇关于如何重写ipython displayhook?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆