Eli Bendersky Eli Bendersky - 1 year ago 188
Python Question

Disable output buffering

Is output buffering enabled by default in Python's interpreter for


If the answer is positive, what are all the ways to disable it?

Suggestions so far:

  1. Use the
    command line switch

  2. Wrap
    in an object that flushes after every write

  3. Set
    env var

  4. sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

Is there any other way to set some global flag in
programmatically during execution?

Seb Seb
Answer Source

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 PYTHONUNBUFFERED.

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):
       self.stream = stream
   def write(self, data):
   def __getattr__(self, attr):
       return getattr(self.stream, attr)

import sys
sys.stdout = Unbuffered(sys.stdout)
print 'Hello'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download