Disable output buffering Disable output buffering python python

Disable output buffering

From Magnus Lycka answer on a mailing list:

You can skip buffering for a wholepython process using "python -u"(or#!/usr/bin/env python -u etc) or bysetting the environment variablePYTHONUNBUFFERED.

You could also replace sys.stdout withsome other stream like wrapper whichdoes a flush after every call.

class Unbuffered(object):   def __init__(self, stream):       self.stream = stream   def write(self, data):       self.stream.write(data)       self.stream.flush()   def writelines(self, datas):       self.stream.writelines(datas)       self.stream.flush()   def __getattr__(self, attr):       return getattr(self.stream, attr)import syssys.stdout = Unbuffered(sys.stdout)print 'Hello'

I would rather put my answer in How to flush output of print function? or in Python's print function that flushes the buffer when it's called?, but since they were marked as duplicates of this one (what I do not agree), I'll answer it here.

Since Python 3.3, print() supports the keyword argument "flush" (see documentation):

print('Hello World!', flush=True)

# reopen stdout file descriptor with write mode# and 0 as the buffer size (unbuffered)import io, os, systry:    # Python 3, open as binary, then wrap in a TextIOWrapper with write-through.    sys.stdout = io.TextIOWrapper(open(sys.stdout.fileno(), 'wb', 0), write_through=True)    # If flushing on newlines is sufficient, as of 3.7 you can instead just call:    # sys.stdout.reconfigure(line_buffering=True)except TypeError:    # Python 2    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Credits: "Sebastian", somewhere on the Python mailing list.