Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

The buffering can be skipped for a whole python process by using "python -u" (or#!/usr/bin/env python -u etc) or you can set the environment variable PYTHONUNBUFFERED.

The sys.stdout can be replaced with some other streams like wrapper which does a flush after every call below is the code that explains how we use sys.stdout:-

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)


Related questions

Browse Categories