Python Unbuffered stdout

I recently discovered that the Python ‘print’ command will buffer IO when writing to the stdout stream, aka the terminal.

In order to flush IO to stdout you must call the flush() after each print statement.

import sys
sys.stdout.write('Hello, world')

Conversely you can open the stdout stream in unbuffered mode.

import sys
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
print 'Hello, world'

Leave a Reply

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