Home > python > Autoflush


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 http://www.gossamer-threads.com/lists/python/python/658167.

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 (autoflush.py) 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
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: