Python – unbuffered stdout in python (as in python -u) from within the program


Possible Duplicate:
Python output buffering

Is there any way to get the effect of running python -u from within my code? Failing that, can my program check if it is running in -u mode and exit with an error message if not? This is on linux (ubuntu 8.10 server)

Best Solution

The best I could come up with:

>>> import os
>>> import sys
>>> unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0)
>>> unbuffered.write('test')
>>> sys.stdout = unbuffered
>>> print 'test'

Tested on GNU/Linux. It seems it should work on Windows too. If I knew how to reopen sys.stdout, it would be much easier:

sys.stdout = open('???', 'w', 0)



Note that it would be probably better to close sys.stdout before overwriting it.