Flush output in for loop in Jupyter notebook

titipata picture titipata · Mar 31, 2017 · Viewed 9.9k times · Source

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?

Answer

âńōŋŷXmoůŜ picture âńōŋŷXmoůŜ · Apr 1, 2017
#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