To flush the output of the print()
function in Python (i.e., force the text to appear immediately in the console instead of waiting for the buffer), use one of the following methods:
1. Use the flush=True
Parameter (Python 3.3+)
Add the flush
parameter to the print()
function to force immediate output:
print("Hello, world!", flush=True) # Flushes the buffer immediately
Example with a Progress Indicator:
import time
for i in range(5):
print(f"Progress: {i+1}/5", end='\r', flush=True) # Overwrite line in real-time
time.sleep(1)
2. Manually Flush sys.stdout
For older Python versions (or explicit control), flush the buffer manually:
import sys
print("Hello, world!") # Buffered output
sys.stdout.flush() # Force buffer flush
3. Disable Buffering Entirely
Run your script with unbuffered output using the -u
flag:
python -u your_script.py
Or set the PYTHONUNBUFFERED
environment variable:
export PYTHONUNBUFFERED=1 # Linux/macOS
python your_script.py
Key Notes
- Default Behavior: By default,
print()
flushes the buffer when a newline (\n
) is printed or when the program ends. - Use Cases: Flushing is critical for real-time logging, progress bars, or when interacting with long-running processes.
- Buffering Modes:
- Unbuffered: Immediate output (e.g.,
python -u
). - Line-Buffered: Flush on newline (default for terminals).
- Block-Buffered: Flush when buffer is full (default for files/redirection).
Example: Real-Time Output in a Loop
Without flushing, this would print all lines at once after the loop ends:
import time
for i in range(3):
print(f"Update {i}") # Buffered (no flush)
time.sleep(1)
With Flushing:
for i in range(3):
print(f"Update {i}", flush=True) # Prints immediately
time.sleep(1)
Summary
- Use
flush=True
inprint()
for simplicity (Python 3.3+). - Use
sys.stdout.flush()
for compatibility with older versions. - Run scripts with
-u
orPYTHONUNBUFFERED
to disable buffering globally.