2014-01-14 155 views
2

我的理解是python會打印輸出的repr,但顯然情況並非總是如此。例如:ipython和python之間的輸出差異

在IPython中:

In [1]: type([]) 
Out[1]: list 

In [2]: set([3,1,2]) 
Out[2]: {1, 2, 3} 

在蟒蛇:

>>> type([]) 
<type 'list'> 
>>> set([3,1,2]) 
set([1, 2, 3]) 

什麼轉變呢IPython中的輸出應用?

+0

IPython版本? –

+0

python'2.7.5'上的ipython'1.1.0' – wim

回答

8

取代repr或標準pprint模塊IPython使用IPython.lib.pretty.RepresentationPrinter.pretty方法至print the output

模塊IPython.lib.pretty提供了在幕後使用RepresentationPrinter.pretty的兩個功能。

IPython.lib.pretty.pretty函數返回一個對象的字符串表示:

>>> from IPython.lib.pretty import pretty 
>>> pretty(type([])) 
'list' 

IPython.lib.pretty.pprint函數打印對象的表示:

>>> from IPython.lib.pretty import pprint 
>>> pprint(type([])) 
list 

IPython的使用,因爲標準的Python pprint模塊「自己的漂亮打印機不允許開發人員提供自己漂亮的打印回調。「

+1

是否在某處記錄了'IPython.lib.pretty.pretty'確實是使用的函數?我做了'IPython.lib.pretty.pretty = lambda * args,** kwargs:'potato'',並且ipython中的輸出沒有變化。 – wim

+0

@wim,很好,我修改了我的答案。 'IPython.lib.pretty.RepresentationPrinter.pretty = lambda * args,** kwargs:sys.stdout.write('12')'將爲任何輸入打印12。 –

+1

請注意,只有'%pprint'魔術開啓時纔會出現這種情況。我默認關閉它,並獲得OP在常規Python提示符處看到的行爲。 – MattDMo