Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flush output in for loop in Jupyter notebook

I want to print out i in my iteration on Jupyter notebook and flush it out. After the next iteration, I'll print the next i. I tried solutions from this question and this question, however, it just print out 0123...9 without flushing the output for me. Here is my working code:

import sys
import time

for i in range(10):
    sys.stdout.write(str(i)) # or print(i, flush=True) ?
    time.sleep(0.5)
    sys.stdout.flush()

these are my setup: ipython 5.1, python 3.6. Maybe, I missed something in the previous solution?

like image 252
titipata Avatar asked Mar 31 '17 21:03

titipata


People also ask

How do you clear the outputs on a Jupyter notebook?

When you have Jupyter notebook opened, you can do this by selecting the Cell -> All Output -> Clear menu item.

What does Clear_output () do in Python?

To clear output in the Notebook you can use the clear_output() function. If you are clearing the output every frame of an animation, calling clear_output() will create noticeable flickering. You can use clear_output(wait=True) to add the clear_output call to a queue.

How do I show full output in Jupyter?

To show the full data without any hiding, you can use pd. set_option('display. max_rows', 500) and pd.


2 Answers

#Try this:
import sys
import time

for i in range (10):  
    sys.stdout.write('\r'+str(i))
    time.sleep(0.5)

'\r' will print at the beginning of the line

like image 91
jose_bacoy Avatar answered Oct 19 '22 07:10

jose_bacoy


The first answer is correct but you don't need sys package. You can use the end parameter of the print function. It specifies what to print at the end, and its default value is \n(newline) (docs1, docs2). Use \r(carriage return) instead.

import time

for i in range (10):  
    print(i, end="\r")
    time.sleep(0.5) # This line is to see if it's working or not
like image 34
Alperen Cetin Avatar answered Oct 19 '22 05:10

Alperen Cetin