Archive
Posts Tagged ‘buffer’
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"
Credits
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:
autoflush(True) # 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
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
Update (20210827)
Here is a Python 3 solution:
# auto-flush
sys.stdout = io.TextIOWrapper(
open(sys.stdout.fileno(), 'wb', 0),
write_through=True
)
Categories: python
autoflush, buffer, context manager, print
