How to flush STDOUT buffer in Python?

How to flush the STDOUT buffer in Python so that the content wrote to STDOUT is shown immediately?

Call the flush library function on sys.stdout which is the STDOUT:

import sys
sys.stdout.flush()

From python doc:

flush()

    Flush the write buffers of the stream if applicable. 
    This does nothing for read-only and non-blocking streams.

If you can’t change the code while you can change the python interpreter options used, you can give it -u:

-u
    Force stdin, stdout and stderr to be totally unbuffered. On
    systems where it matters, also put stdin, stdout and stderr
    in binary mode. Note that there is internal buffering in 
    xreadlines(), readlines() and file-object iterators ("for 
    line in sys.stdin") which is not influenced by this option. 
    To work around this, you will want to use 
    "sys.stdin.readline()" inside a "while 1:" loop.

If you can’t change the interpreter options either, there is another way too by setting the environment variable PYTHONUNBUFFERED:

PYTHONUNBUFFERED
    If this is set to a non-empty string it is equivalent to 
    specifying the -u option.

Reference: python2.7 manual

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *