IPython:打印字符串结果

IPython: Print string results

我想让 IPython 自动打印所有 str 个结果。

In [13]: 'hi\nhi' # I don't want this output
Out[13]: 'hi\nhi'

In [14]: print(_) # I want it like this, but without using print on every result.
hi
hi

这是一个非常肮脏的 hack,但你可以猴子修补 IPython.lib.pretty.RepresentationPrinter:

In [9]: import IPython.lib.pretty                                                                                                                                                                     

In [10]: class NewPrettier(IPython.lib.pretty.RepresentationPrinter): 
    ...:     def pretty(self, obj): 
    ...:         if isinstance(obj, (str,)): 
    ...:             self.text(obj) 
    ...:         else: 
    ...:             super().pretty(obj) 
    ...:                                                                                                                                                                                              

In [11]: IPython.lib.pretty.RepresentationPrinter = NewPrettier                                                                                                                                       

In [12]: "a"                                                                                                                                                                                          
Out[12]: a

编辑:删除 Out[n]:

In [24]: import IPython.core.displayhook                                                                                                                                                              

In [25]: IPython.core.displayhook.DisplayHook.write_output_prompt = lambda :None                                                                                                                      

In [26]: "X"                                                                                                                                                                                          
X