是否有可能改变IPython的漂亮打印机?

时间:2016-02-13 01:43:18

标签: python ipython pprint

是否可以更改IPython使用的漂亮打印机?

我想切换pprint++的默认漂亮打印机,我更喜欢嵌套结构之类的东西:

In [42]: {"foo": [{"bar": 42}, {"bar": 16}] * 3, "bar": [1,2,3,4,5]}
Out[42]: 
{'bar': [1, 2, 3, 4, 5],
 'foo': [{'bar': 42},
  {'bar': 16},
  {'bar': 42},
  {'bar': 16},
  {'bar': 42},
  {'bar': 16}]}

In [43]: pprintpp.pprint({"foo": [{"bar": 42}, {"bar": 16}] * 5, "bar": [1,2,3,4,5]})
{
    'bar': [1, 2, 3, 4, 5],
    'foo': [
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
    ],
}

1 个答案:

答案 0 :(得分:5)

从技术上讲,这可以通过在IPython中修补使用here的类IPython.lib.pretty.RepresentationPrinter来完成。

这就是人们可以这样做的方式:

In [1]: o = {"foo": [{"bar": 42}, {"bar": 16}] * 3, "bar": [1,2,3,4,5]}

In [2]: o
Out[2]: 
{'bar': [1, 2, 3, 4, 5],
 'foo': [{'bar': 42},
  {'bar': 16},
  {'bar': 42},
  {'bar': 16},
  {'bar': 42},
  {'bar': 16}]}

In [3]: import IPython.lib.pretty

In [4]: import pprintpp

In [5]: class NewRepresentationPrinter:
            def __init__(self, stream, *args, **kwargs):
                self.stream = stream
            def pretty(self, obj):
                p = pprintpp.pformat(obj)
                self.stream.write(p.rstrip())
            def flush(self):
                pass


In [6]: IPython.lib.pretty.RepresentationPrinter = NewRepresentationPrinter

In [7]: o
Out[7]: 
{
    'bar': [1, 2, 3, 4, 5],
    'foo': [
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
        {'bar': 42},
        {'bar': 16},
    ],
}

出于多种原因,这是一个坏主意,但从技术角度来说应该是现在。目前似乎并没有一种官方的,支持的方式来覆盖IPython中的所有漂亮打印,至少是简单的。

(注意:需要.rstrip()因为IPython不期望结果上有一个尾随换行符)

相关问题