This article mainly introduces the stdout output non-Cache setting method in python. This method is only used in special environments. For more information, consider the following python program:
The Code is as follows:
#! /Usr/bin/env python
Import sys
Sys. stdout. write ("stdout1 ")
Sys. stderr. write ("stderr1 ")
Sys. stdout. write ("stdout2 ")
Sys. stderr. write ("stderr2 ")
The sys. stdout. write can also be replaced with print.
What do you think will be output when you run this program? After testing, we will find that the output is not
The Code is as follows:
Stdout1 stderr1 stdout2 stderr2
But:
The Code is as follows:
Stderr1 stderr2 stdout1 stdout2
The reason is that cache: Although both stderr and stdout point to the screen by default, stderr is not cached. If the program outputs a character to stderr, it will display one on the screen; stdout has a cache. It is displayed only when a line break or a certain size is accumulated. This is why the above two stderr entries are displayed.
However, sometimes, you may still want stdout to behave the same way as stderr. Can it be implemented? Of course, this is acceptable, and it is very convenient to implement python. The following are two methods:
The Code is as follows:
Python-u stderr_stdout.py
PYTHONUNBUFFERED = 1 python stderr_stdout.py
The first method is to specify the-u parameter for python, and the second method is to specify the PYTHONUNBUFFERED environment variable during python runtime. These two methods are actually equivalent.
Of course, you can also specify # In the first line of the program #! /Usr/bin/python-u and then add executable permissions to the program to run, or write export PYTHONUNBUFFERED = 1 to. bashrc.
Appendix: stackoverflow has similar problems. For details, refer
Address: http://stackoverflow.com/questions/107705/python-output-buffering
Adopted code:
The Code is as follows:
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'