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?
sleep() and the User Experience To add suspense, I use the sleep() function to delay by about a second after each word is printed.
Summary: Python sleep() function will pause Python code or delay the execution of program for the number of seconds given as input to sleep(). The sleep() function is part of the Python time module. You can make use of Python sleep function when you want to temporarily halt the execution of your code.
sleep() Python has built-in support for putting your program to sleep. The time module has a function sleep() that you can use to suspend execution of the calling thread for however many seconds you specify.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With