Posts Tagged ‘autoflush’


September 27, 2010 Leave a comment

Printing to the standard output is buffered. What to do if you want to see the output immediately?

import sys
import os

# reopen stdout file descriptor with write mode
# and 0 as the buffer size (unbuffered)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

print "unbuffered text"


This tip is from

Update (20130206)
The solution above switches buffered mode off, but you can’t switch it back on because you lose the original sys.stdout file descriptor. I have a more sophisticated solution, available here ( as part of my jabbapylib library.

Usage #1:

# text that you want to print in unbuffered mode comes here
autoflush(False)    # back to normal

Usage #2:

# using a context manager
with AutoFlush():
    # unbuffered text comes here

# here you are back to normal

Let’s not forget the simplest and most trivial solution either:

sys.stdout.flush()    # flush out immediately