Make ipython notebook print in real time
This is merely one of the answers to the question suggested by Carsten incorporating the __getattr__
delegation suggested by diedthreetimes in a comment:
import sysoldsysstdout = sys.stdoutclass flushfile(): def __init__(self, f): self.f = f def __getattr__(self,name): return object.__getattribute__(self.f, name) def write(self, x): self.f.write(x) self.f.flush() def flush(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
Since Python 3.3, print()
has an additional flush argument that can be used to force flushing:
for i in range(10): print(i, flush=True) time.sleep(1)
Try this:
from IPython.display import display, clear_outputdisplay("Hello World") # print stringdisplay(df) # print object such as dataframeclear_output(wait=True) # use this if need to clear the output before display, good for dynamic updates