Why print in Python doesn’t pause when using sleep in a loop?

print, by default, prints to sys.stdout and that buffers the output to be printed, internally.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

Changed in version 3.3: Added the flush keyword argument.

Quoting sys.stdout‘s documentation,

When interactive, standard streams are line-buffered. Otherwise, they are block-buffered like regular text files.

So, in your case, you need to explicitly flush, like this

import time
for i in range(10):
    print(i, flush=True)
    time.sleep(.5)

Okay, there is a lot of confusion around this buffering. Let me explain as much as possible.

First of all, if you are trying this program in a terminal, they do line buffering (which basically means, whenever you encounter a newline character, send the buffered data to stdout), by default. So, you can reproduce this problem in Python 2.7, like this

>>> import time
>>> for i in range(10):
...     print i,
...     time.sleep(.5)
... 

And in Python 3.x,

>>> for i in range(10):
...     print(i, end='')
...     time.sleep(.5)

We pass end='' because, the default end value is \n, as per the print‘s documentation,

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Since the default end breaks the line buffering, the data will be sent to stdout immediately.

Another way to reproduce this problem is to store the actual program given by OP in a file and execute with Python 3.x interpreter, you will see that the stdout internally buffers the data and waits till the program finishes to print.

Leave a Comment