Flush Python print output immediately

Use flush=True, stdout.flush(), or unbuffered Python output, and distinguish application buffering from log delivery and durable disk writes.

Best practices
Python programming and application logging

Use print(..., flush=True) when a message should leave Python's output buffer immediately. This is useful for progress messages without a newline and for programs whose output goes to a pipe.

Flush a single print call

print("Processing started", flush=True)
print("Working...", end="", flush=True)

The option has been available since Python 3.3. It flushes the selected output stream after writing.

Flush at a chosen boundary

import sys

print("First update")
print("Second update")
sys.stdout.flush()

This lets several writes share one flush. It applies to sys.stdout; if you printed to another file, flush that file instead.

Run with unbuffered standard output

python -u script.py

Alternatively, set PYTHONUNBUFFERED=1 in the process environment. These options affect Python's standard output and error streams, not every file the program opens.

Interactive stdout is normally line buffered; stdout connected to a file or pipe is normally block buffered. Buffer sizes and replacement stream behavior vary, so do not depend on a fixed number of bytes or seconds before output appears. Unbuffered output is often useful for containerized programs that use print for status messages.

Account for downstream delays

A flush does not guarantee that a terminal, container log driver, remote collector, or storage system has displayed or persisted the message. Compare application timestamps with collector reception times if logs still arrive late.

FAQ

Does logging need the same treatment? Standard StreamHandler flushes after emitting a record; FileHandler inherits that behavior. Queue-based or third-party handlers can introduce their own buffering.

Does flushing cost more? Frequent flushes can increase output overhead. Measure the workload and batch high-volume status output where immediate delivery is unnecessary.

How do I make file data durable? Flush Python's buffer, then ask the operating system to synchronize the file:

import os

with open("result.txt", "w", encoding="utf-8") as output:
    output.write("completed\n")
    output.flush()
    os.fsync(output.fileno())

Durability also depends on the filesystem and storage stack. RotatingFileHandler manages file size and rollover; it does not automatically provide fsync durability for every record.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting