Search code examples
pythonprintingoverwriteflushsys

Python sys.stdout.flush() doesn't seem to work


I want to see the progress of my for loop by repeatedly overwriting the print function. I expected the printed line to be overwritten every time the loop progresses. What happened was that after every loop a new line was printed right under the previous printed line. This was solved by removing the \n from the print line, because the \n caused a new empty line to be overwritten each time, instead of overwriting the first printed line.

import sys
import time

count1=0
x=10
for i in range(x):
    count1+=1
    sys.stdout.write("\r{} out of {}...\n".format(count1, x))
    sys.stdout.flush()
    time.sleep(.1)

I am using Python 3.6 (64-bit) in Jupter Notebook 4.3.1. on Windows 10.

I have looked over several issues posted on Stack Overflow, but I haven't been able to solve it yet.

Thanks!


Solution

  • Remove the "\n" that creates a new line.

    sys.stdout.write("\r{} out of {}...".format(count1, x))