I've got an extremely simple application:
import sys
from time import sleep
for i in range(3):
sys.stdout.write('.')
sleep(1)
print('Welcome!')
I expect it to print out a dot every second (3 times), after which it should display "Welcome!". Unfortunately, it simply waits three seconds, and then prints out everything at once. I'm on a mac running regular Python 2.7 and I have no clue why this code behaves like this. Any suggestions?
When we are directly writing outputs to our terminal, each writing operation is being done “synchronously”, which means our programs waits for the “write” to complete before it continues to the next commands. Each time our programs writes something to stdout , we are met with this delay.
Make your time delay specific by passing a floating point number to sleep() . from time import sleep print("Prints immediately.") sleep(0.50) print("Prints after a slight delay.")
For adding time delay during execution we use the sleep() function between the two statements between which we want the delay. In the sleep() function passing the parameter as an integer or float value. Run the program.
If you've got a Python program and you want to make it wait, you can use a simple function like this one: time. sleep(x) where x is the number of seconds that you want your program to wait.
It's because sys.stdout
is buffered. Use flush
:
import sys
from time import sleep
for i in range(3):
sys.stdout.write('.')
sys.stdout.flush()
sleep(1)
print('Welcome!')
You can call python with -u
to make stdin, stdout, and stderr totally unbuffered. This would save you from having to manually flush them.
On Unix, call your script like python -u myscript.py
Or you can put it in the shebang: #!/usr/bin/python -u
stdout
is a buffered stream. The buffer is flushed implicitly when it reaches a newline character.
If you want to flush the buffer without writing a newline character, you must do so explicitly by calling sys.stdout.flush()
Another alternative is to write to stderr
, which is not buffered.
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