Pass flush=True directly to print() (print("Processing...", flush=True)), call sys.stdout.flush() explicitly, or launch Python with the -u unbuffered flag (python -u script.py) / PYTHONUNBUFFERED=1 environment variable so stdout writes appear immediately in terminals, Docker logs, CI pipelines, and redirected files without waiting for a newline or buffer fill.
Basic Example
import sys
import time
# 1. Recommended (per-call): Pass `flush=True` directly to `print()`
for step in range(1, 4):
print(f"Step {step}/3...", end=" ", flush=True)
time.sleep(0.5)
print("Done!")
# Output (appears progressively every 0.5s instead of all at once after 1.5s):
# Step 1/3... Step 2/3... Step 3/3... Done!
# 2. Explicit stream flush (useful after multiple prints or sys.stdout.write()):
sys.stdout.write("Loading")
sys.stdout.flush()
# 3. Process-wide unbuffered output (ideal for Docker containers & CI/CD logs):
python -u app.py
# Or via environment variable:
PYTHONUNBUFFERED=1 python app.py
Key Details & Edge Cases
- Why Python buffers
stdoutdifferently in interactive terminals vs. pipes/files:- When
sys.stdoutis connected to an interactive terminal (TTY), Python uses line buffering—meaningprint("msg")flushes automatically on\n, except when you suppress the newline withend=""orend=" "(common in progress bars or"Loading..."indicators), where output stays stuck in memory until\nor program exit. - When
sys.stdoutis redirected to a file, pipe, systemd service, or Docker container (non-TTY), Python switches to block buffering (typically 4 KB–8 KB chunks), delaying even newline-terminatedprint()calls until the buffer fills or the process exits.
- When
- Changing buffering globally at runtime (
sys.stdout.reconfigure(line_buffering=True)):- In Python 3.7+, if you cannot pass
-uon the command line (for example, inside a packaged entrypoint or Jupyter/worker process), reconfiguresys.stdoutonce at startup so every subsequentprint()with a newline flushes immediately even when redirected:import sys sys.stdout.reconfigure(line_buffering=True)
- In Python 3.7+, if you cannot pass
sys.stderris unbuffered (or line-buffered) by default:- Error and diagnostic messages written to
sys.stderr(print("Error!", file=sys.stderr)) bypass block buffering automatically, though passingflush=Trueis still needed when omitting the trailing newline (end="").
- Error and diagnostic messages written to
- Performance cost of
flush=Trueinside tight loops:- Every
flush=Truetriggers an OSwrite()system call. Callingprint(..., flush=True)inside a tight loop of millions of iterations can slow execution by 10x–50x—throttle progress prints (e.g.,if i % 1000 == 0: print(..., flush=True)) or usetqdm/rich.progress.
- Every
- Logging module vs.
print(..., flush=True):- Python’s standard
logging.StreamHandlerautomatically calls.flush()after every emitted log record by default, makingloggingpreferable overprint()for production services and long-running background workers.
- Python’s standard
Comparison of Output-Flushing Methods in Python
| Method | Scope | Works When end="" (No Newline)? |
Works When Redirected to File / Docker Pipe? | Best Used When |
|---|---|---|---|---|
print(..., flush=True) (Recommended) |
Single print() call |
Yes | Yes | Progress indicators (end="" / end="\r"), interactive prompts, and critical status checkpoints. |
sys.stdout.flush() |
All buffered bytes up to call | Yes | Yes | Flushing after sys.stdout.write() or batching several print() calls before a single flush. |
python -u / PYTHONUNBUFFERED=1 |
Entire Python process (stdout & stderr) |
Yes | Yes | Dockerfiles, Kubernetes pods, CI/CD jobs, and background scripts where all logs must stream live. |
sys.stdout.reconfigure(line_buffering=True) |
Entire process from call onward | No (flushes on \n only) |
Yes (enables TTY-style line buffering on pipes) | Enforcing real-time line-by-line log streaming in Python 3.7+ scripts without CLI flags. |
You must log in or register to comment.
