Is output buffering enabled by default in Python's interpreter for sys.stdout
?
If the answer is positive, what are all the ways to disable it?
Suggestions so far:
- Use the
-u
command line switch - Wrap
sys.stdout
in an object that flushes after every write - Set
PYTHONUNBUFFERED
env var sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Is there any other way to set some global flag in sys
/sys.stdout
programmatically during execution?
You can also run Python with stdbuf utility:
stdbuf -oL python <script>
You can also use fcntl to change the file flags in-fly.
Variant that works without crashing (at least on win32; python 2.7, ipython 0.12) then called subsequently (multiple times):
It is possible to override only
write
method ofsys.stdout
with one that callsflush
. Suggested method implementation is below.Default value of
w
argument will keep originalwrite
method reference. Afterwrite_flush
is defined, the originalwrite
might be overridden.The code assumes that
stdout
is imported this wayfrom sys import stdout
.Without saving the old sys.stdout, disable_stdout_buffering() isn't idempotent, and multiple calls will result in an error like this:
Another possibility is:
(Appending to gc.garbage is not such a good idea because it's where unfreeable cycles get put, and you might want to check for those.)
This relates to Cristóvão D. Sousa's answer, but I couldn't comment yet.
A straight-forward way of using the
flush
keyword argument of Python 3 in order to always have unbuffered output is:afterwards, print will always flush the output directly (except
flush=False
is given).Note, (a) that this answers the question only partially as it doesn't redirect all the output. But I guess
print
is the most common way for creating output tostdout
/stderr
in python, so these 2 lines cover probably most of the use cases.Note (b) that it only works in the module/script where you defined it. This can be good when writing a module as it doesn't mess with the
sys.stdout
.Python 2 doesn't provide the
flush
argument, but you could emulate a Python 3-typeprint
function as described here https://stackoverflow.com/a/27991478/3734258 .