How can I flush the output of the print function?

Published on Aug. 22, 2023, 12:16 p.m.

In Python, you can use the optional flush parameter of the print() function to force the output to be immediately displayed. This parameter will make sure that any output that is buffered goes to the destination, even if the buffer is not full. Here is an example:

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

Alternatively, you can use the sys.stdout.flush() function to flush any buffered output to the console. Here is an example:

import sys
print("Hello, World!")
sys.stdout.flush()

This will print “Hello, World!” to the console immediately, even if there are other outputs in the buffer. Note that the flush() method only works with Python 3, while the use of sys.stdout.flush() works with both Python 2 and 3.

Tags:

related content