Stdout in python outputs an uncached setting method

  • 2020-04-02 13:41:36
  • OfStack

Consider the following python programs:


#!/usr/bin/env python

import sys

sys.stdout.write("stdout1 ")
sys.stderr.write("stderr1 ")
sys.stdout.write("stdout2 ")
sys.stderr.write("stderr2 ")

Sys. stdout.write can also be replaced by print.
Running this program, what do you think will be output? Experiment, and you'll see that the output isn't

stdout1 stderr1  stdout2 stderr2

But:

stderr1 stderr2 stdout1  stdout2

The reason is because of the cache: although stderr and stdout are both pointing to the screen by default, stderr is cache-free. Stdout is cached and will only be displayed when a new line is encountered or a certain size is accumulated. This is why the above shows two stderrs.
However, sometimes you want stdout to behave like stderr. Of course you can, and for python, it's extremely easy to implement. Here are two ways:

python -u stderr_stdout.py
PYTHONUNBUFFERED=1 python stderr_stdout.py

The first way is to give python the -u parameter, and the second way is to specify the PYTHONUNBUFFERED environment variable while python is running, which are actually equivalent.
Of course, you can also specify #! On the first line of your program /usr/bin/python-u then runs the program with executable permissions, or write export PYTHONUNBUFFERED=1 to.bashrc.


P.S. some students have encountered similar problems on stackoverflow, please refer to them

Address: http://stackoverflow.com/questions/107705/python-output-buffering

Code adopted:


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


Related articles: