python - Usage of sys.stdout.flush() method

python – Usage of sys.stdout.flush() method

python – Usage of sys.stdout.flush() method

Pythons standard out is buffered (meaning that it collects some of the data written to standard out before it writes it to the terminal). Calling sys.stdout.flush() forces it to flush the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.

Heres some good information about (un)buffered I/O and why its useful:
http://en.wikipedia.org/wiki/Data_buffer
Buffered vs unbuffered IO

Consider the following simple Python script:

import time
import sys

for i in range(5):
    print(i),
    #sys.stdout.flush()
    time.sleep(1)

This is designed to print one number every second for five seconds, but if you run it as it is now (depending on your default system buffering) you may not see any output until the script completes, and then all at once you will see 0 1 2 3 4 printed to the screen.

This is because the output is being buffered, and unless you flush sys.stdout after each print you wont see the output immediately. Remove the comment from the sys.stdout.flush() line to see the difference.

python – Usage of sys.stdout.flush() method

As per my understanding, When ever we execute print statements output will be written to buffer. And we will see the output on screen when buffer get flushed(cleared). By default buffer will be flushed when program exits. BUT WE CAN ALSO FLUSH THE BUFFER MANUALLY by using sys.stdout.flush() statement in the program. In the below code buffer will be flushed when value of i reaches 5.

You can understand by executing the below code.

[email protected]:~$ cat flush.py
import time
import sys

for i in range(10):
    print i
    if i == 5:
        print Flushing buffer
        sys.stdout.flush()
    time.sleep(1)

for i in range(10):
    print i,
    if i == 5:
        print Flushing buffer
        sys.stdout.flush()
[email protected]:~$ python flush.py 
0 1 2 3 4 5 Flushing buffer
6 7 8 9 0 1 2 3 4 5 Flushing buffer
6 7 8 9

Related posts on python  :

Leave a Reply

Your email address will not be published. Required fields are marked *