2016-02-13 63 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'就行了。謝謝! –