Flush output in for loop in Jupyter notebook
Asked Answered
G

3

13

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?

Gupton answered 31/3, 2017 at 21:42 Comment(0)
C
15
#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

Cyclorama answered 31/3, 2017 at 23:1 Comment(1)
thanks! this solution works for me. seems like we don't really need flush output at all.Gupton
L
10

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
Loop answered 17/4, 2019 at 21:39 Comment(1)
Thanks @Alperen! This one is actually handy!Gupton
B
3

Try this

for i in range (10):  
    print("\r", end=str(i))
Bunin answered 7/11, 2020 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.