2016-02-13 103 views
2

是否可以更改IPython使用的漂亮打印机?是否可以更改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}, 
    ], 
} 
+0

还有的是一票打开该功能在这里:https://github.com/ipython/ipython/issues/9227 –

回答

4

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

这是一个可以如何做到这一点:

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的预计不会对结果的尾随的换行符)

+0

我喜欢坏主意!进入我的'ipy_user_conf.py'就行了。谢谢! –