Python print statements happening "in batch" instead of one at a time

Issue

Consider the following python code:

import time

if __name__ == '__main__':
    for i in range(10):
        time.sleep(1)
        print(i)    

Running this code as a shell script (using the Terminal app on MacOS, if that’s relevant) does what I expect: after every second, a number is printed to the screen.

However, I also considered the following modified code in which the print statement is changed:

import time

if __name__ == '__main__':
    for i in range(10):
        time.sleep(1)
        print(i, end=' ')    

Here, the code doesn’t print a number per second, but rather it waits 10 seconds and then prints all of the numbers to the screen simultaneously. I’m wondering why this is happening, and if there is a way to fix this so that the numbers print one at a time like in the first example?

Solution

this should work just fine

import time

if __name__ == '__main__':
    for i in range(10):
        print(i, end=' ',flush=True)
        time.sleep(1)

      

Answered By – omar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published