ipython notebook clear cell output in code


In a iPython notebook, I have a while loop that listens to a Serial port and print the received data in real time.

What I want to achieve to only show the latest received data (i.e only one line showing the most recent data. no scrolling in the cell output area)

What I need(i think) is to clear the old cell output when I receives new data, and then prints the new data. I am wondering how can I clear old data programmatically ?

Asked By: aha



You can use IPython.display.clear_output to clear the output of a cell.

from IPython.display import clear_output

for i in range(10):
    print("Hello World!")

At the end of this loop you will only see one Hello World!.

Without a code example it’s not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell’s output and print the buffer again.

Answered By: cel

And in case you come here, like I did, looking to do the same thing for plots in a Julia notebook in Jupyter, using Plots, you can use:


so for a kind of animated plot of multiple runs

    if nrun==1  
      display(plot(x,y))         # first plot
      IJulia.clear_output(true)  # clear the window (as above)
      display(plot!(x,y))        # plot! overlays the plot

Without the clear_output call, all plots appear separately.

Answered By: marzetti

You can use the IPython.display.clear_output to clear the output as mentioned in cel’s answer. I would add that for me the best solution was to use this combination of parameters to print without any “shakiness” of the notebook:

from IPython.display import clear_output

for i in range(10):
    print(i, flush=True)
Answered By: hof.and.or

You can have a better visualization of the function clear_output(wait=True) with this simple code.

from IPython.display import clear_output
import time 

for i in range(10):
Answered By: vaibhav singh

If I am not wrong you mean you just need to clear the output part of a cell, which could be a valid output or some error which you don’t what to look anymore. If Yes! just go to top ribbon and select Cell > Current Outputs > Clear

Answered By: VinitV

if you want to clear the output of that current cell only just use this at the end of that cell

from IPython.display import clear_output
Answered By: Deepanshu Mehta
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.