Skip to content Skip to sidebar Skip to footer

Make Ipython Notebook Print In Real Time

Ipython Notebook doesn't seem to print results in real time, but seems to buffer in a certain way and then bulk output the prints. How can I make ipython print my results as soon a

Solution 1:

This is merely one of the answers to the question suggested by Carsten incorporating the __getattr__ delegation suggested by diedthreetimes in a comment:

import sys
oldsysstdout = sys.stdout
classflushfile():
    def__init__(self, f):
        self.f = f
    def__getattr__(self,name): 
        returnobject.__getattribute__(self.f, name)
    defwrite(self, x):
        self.f.write(x)
        self.f.flush()
    defflush(self):
        self.f.flush()
sys.stdout = flushfile(sys.stdout)

In the original answer, the __getattr__ method is not implemented. Without that, it fails. Other variants in answers to that question also fail in a notebook.

In a notebook, sys.stdout is an instance of IPython.kernel.zmq.iostream.OutStream and has a number of methods and attributes not present in the usual sys.stdout. Delegating __getattr__ allows a flushfile to masquerade as a ...zmq.iostream.OutStream duck.

This works in a python 2.7 notebook run with ipython 3.1.0

Solution 2:

Solution 3:

Try this:

from IPython.display import display, clear_output

display("Hello World") # print string
display(df) # print object such as dataframe

clear_output(wait=True) # use this if need to clear the output before display, good for dynamic updates

Solution 4:

Additionally, you can use the carriage return character:

fromtime import sleep
for i in range(10):
    print(i, end='\r')
    sleep(1)

Or if you're using Jupyter Notebooks:

from IPython.display import clear_output
fromtime import sleep
for i in range(10):
    print(i)
    sleep(1)
    clear_output(wait=True) 

Post a Comment for "Make Ipython Notebook Print In Real Time"