Home >Backend Development >Python Tutorial >How Can I Force Immediate Output from the `print` Function in Python?
Explicitly Flushing the Print Output
In Python, print function output is buffered, meaning it's temporarily stored in memory and only displayed once the buffer fills up or when a newline is added. To force an immediate display without using a newline, you can manually flush the buffer.
Python 3
In Python 3, the print function includes an optional flush argument. Passing True to this argument instructs Python to flush the output immediately:
print("Hello, World!", flush=True)
Python 2
In Python 2, there is no flush argument available. Instead, use the following code to flush the stdout buffer after calling print:
import sys sys.stdout.flush()
Sys.stdout represents the standard output (the terminal), and the flush() method forces the buffer to be written.
Note:
By default, print writes to sys.stdout. For more information on file objects used in Python, refer to the official documentation.
The above is the detailed content of How Can I Force Immediate Output from the `print` Function in Python?. For more information, please follow other related articles on the PHP Chinese website!