HappyFace
HappyFace

Reputation: 4093

IPython: Print string results

I want to make IPython automatically print all str results.

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

Upvotes: 2

Views: 116

Answers (1)

RafalS
RafalS

Reputation: 6324

It's a really dirty hack but you can monkey-patch the 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

EDIT: to remove Out[n]:

In [24]: import IPython.core.displayhook                                                                                                                                                              

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

In [26]: "X"                                                                                                                                                                                          
X

Upvotes: 3

Related Questions