Search code examples
pythonprintingflushoutput-buffering

How can I flush the output of the print function?


How do I force Python's print function to flush the buffered output to the screen?


See also: Disable output buffering if the goal is to change the buffering behaviour generally. This question is about explicitly flushing output after a specific print call, even though output is still being buffered.

For duplicate closers: if a beginner is asking a question about trying to make output appear immediately while not using a newline at the end, please instead use Why doesn't print output show up immediately in the terminal when there is no newline at the end? to close the question. The current question isn't good enough because the person asking will likely not have a concept of buffering or flushing; the other question is intended to explain those concepts first, whereas this question is about the technical details.


Solution

  • In Python 3, print can take an optional flush argument:

    print("Hello, World!", flush=True)
    

    In Python 2, after calling print, do:

    import sys
    sys.stdout.flush()
    

    By default, print prints to sys.stdout (see the documentation for more about file objects).