Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my python output delayed to the end of the program?

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?

like image 951
kramer65 Avatar asked Jul 12 '13 08:07

kramer65


People also ask

Why is stdout slow?

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.

How to delay printing in Python?

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.")

How to delay text on Python?

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.

How to give wait time in Python?

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.


3 Answers

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!')
like image 71
zhangyangyu Avatar answered Oct 20 '22 06:10

zhangyangyu


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

like image 28
ajwood Avatar answered Oct 20 '22 06:10

ajwood


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.

like image 41
Henrik Avatar answered Oct 20 '22 07:10

Henrik