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.
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.
autoflush(True) # text that you want to print in unbuffered mode comes here autoflush(False) # back to normal
# using a context manager with AutoFlush(): # unbuffered text comes here sys.stdout.write(...) # here you are back to normal
Let’s not forget the simplest and most trivial solution either:
sys.stdout.write(...) sys.stdout.flush() # flush out immediately