0

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?

Solarflare0
  • 269
  • 2
  • 5
  • 1
    More precisely, it's waiting until the buffer is full or the script ends, whichever comes first. Waiting 10 seconds is a consequence of the script exiting after the loop completes, which takes 10 seconds. – chepner Jul 27 '22 at 23:37

2 Answers2

1

this should work just fine

import time

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

      
omar
  • 258
  • 2
  • 6
1

Adding the flush=True (see here) keyword disables the buffering of the print function.

import time

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