10
votes

This code:

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

Causes my computer to hang for 5 seconds, and then print out 0-9, as opposed to printing a digit every half second. Am I doing something wrong?

2
I don't know much python, but do you need to print a newline character to have the output printed to the console? - Mathemats
no, As I said, this does print the digits, just without a delay in between them. - Startec
it working fine on my computer - Afriyandi Setiawan
Working fine on mine too. Do you maybe have an indentation issue? For the record I'm using python3.4 - user2027202827
@Startec I am able to reproduce the problem and I have explained the solution in my answer, please check. Others, don't use the interactive shell, which is line-buffered, try writing the code in a file and execute it with the interpreter. - thefourtheye

2 Answers

16
votes

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.

0
votes

Try this:

for i in range(10):
        sys.stdout.write('\r' + str(i))
        time.sleep(.5)

here '/r' is carriage return, it brings the cursor first place again.