Fix Python – Disable output buffering


Asked By – Eli Bendersky

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:

  1. Use the -u command line switch
  2. Wrap sys.stdout in an object that flushes after every write
  4. 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?

Now we will see solution for issue: Disable output buffering


From Magnus Lycka answer on a mailing list:

You can skip buffering for a whole
python process using python -u
(or #!/usr/bin/env python -u etc.) or by
setting the environment variable

You could also replace sys.stdout with
some other stream like wrapper which
does a flush after every call.

class Unbuffered(object):
   def __init__(self, stream): = stream
   def write(self, data):
   def writelines(self, datas):
   def __getattr__(self, attr):
       return getattr(, attr)

import sys
sys.stdout = Unbuffered(sys.stdout)
print 'Hello'

This question is answered By – Seb

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0