Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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

  3. Set PYTHONUNBUFFERED env var

  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):

           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 sys

sys.stdout = Unbuffered(sys.stdout)

print('Hello')

Related questions

Browse Categories

...