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?

asked Sep 6 by Eric Z Ma (43,600 points)

1 Answer

 
Best answer

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

answered Sep 6 by Eric Z Ma (43,600 points)
selected Sep 6 by Eric Z Ma

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...