Question

Flush Print Output in Python: print() Buffering and flush=True

pythonprintingflushoutput-buffering

Question

How can I force Python's print() function to flush its buffered output immediately after a specific call, so that the output is written to the terminal or its destination without waiting for the buffer to fill or the program to finish?

For example:

print("Processing...")
# Force this output to be flushed now

Short Answer

Python output is often buffered: text may be temporarily held before it is written to a terminal, file, pipe, or another output destination. By the end of this page, you will know how to flush one print() call with flush=True, flush a stream manually with sys.stdout.flush(), and choose the right approach for progress messages and long-running programs.

Concept

print() writes text to an output stream, normally sys.stdout. That stream may use a buffer, which is temporary storage that collects output before sending it onward.

Buffering improves performance because writing many small pieces of text individually can be inefficient. However, buffering can be undesirable when a user needs to see a status message immediately, such as before a slow task begins.

Python's print() function has a flush keyword argument:

print("Starting download...", flush=True)

When flush=True is used, Python writes the text and then asks the output stream to flush its pending buffered data.

Flushing is useful for a specific output operation. It does not necessarily guarantee that text has physically appeared on every possible display device; it tells Python's stream to pass along buffered content as soon as possible. Other layers, such as an operating system, terminal, pipe, or logging system, can have their own behavior.

Mental Model

Think of output buffering as placing letters in an outgoing-mail tray.

  • print() puts a letter in the tray.
  • Normally, the tray is sent when it is full, when a newline triggers line-buffered behavior in an interactive terminal, or when the program ends.
  • flush=True is like telling the mailroom: “Send everything in the tray right now.”

This is useful when the recipient needs an update before you continue with a slow task.

Take Quiz

Syntax and Examples

Use flush=True for an individual print() call:

print(*objects, sep=" ", end="\n", file=None, flush=False)

Set flush=True when immediate output matters:

import time

print("Connecting to server...", flush=True)
time.sleep(2)
print("Connected.")

The first message is flushed before the program waits for two seconds.

You can also flush sys.stdout directly:

import sys

print("Connecting to server...")
sys.stdout.flush()

This is especially useful if several writes should be flushed together:

import sys

print("Downloading", end="")
print(".", end="")
print(".", end="")
sys.stdout.flush()

For most single print() calls, flush=True is clearer and more concise.

Step by Step Execution

Consider this program:

import time

print("Preparing report...", flush=True)
time.sleep(3)
print("Report complete.")

Execution trace:

  1. Python imports the time module.
  2. print("Preparing report...", flush=True) writes the message to standard output.
  3. Because flush=True is set, Python immediately flushes sys.stdout.
  4. The user can see Preparing report... before the next line runs.
  5. time.sleep(3) pauses the program for three seconds.
  6. Python prints Report complete..

Without flush=True, whether the first message appears before the pause depends on the output destination and its buffering mode. Interactive terminals often show newline-terminated output promptly, but redirected output and pipes may behave differently.

Real World Use Cases

Common situations for explicit flushing include:

  • Command-line tools: Show Loading configuration... before a slow network request.
  • Progress indicators: Update one terminal line with end="\r" while processing files.
  • Containerized applications: Make diagnostic output visible promptly in Docker or CI logs.
  • Pipelines: Send output to another command that should receive data without waiting for a large buffer.
  • Interactive scripts: Prompt a user before calling code that waits for input or performs a long task.
  • Debugging a hang: Print and flush checkpoints to discover which operation the program reached.

Example progress display:

import time

for percent in range(0, 101, 25):
    print(f"Progress: {percent}%", end="\r", flush=True)
    time.sleep(1)

print("Done.             ")
Take Quiz

Real Codebase Usage

In production code, explicit flushing is usually reserved for user-facing command-line feedback or operational diagnostics. Avoid adding flush=True to every print() call without a reason, since buffering exists partly for efficiency.

Status message before slow work

print("Uploading backup...", flush=True)
upload_backup()
print("Upload finished.")

Flush a custom stream

print() can write to a file-like object. The flush=True argument flushes that target after writing.

with open("events.txt", "a", encoding="utf-8") as log_file:
    print("Backup started", file=log_file, flush=True)

Prefer logging for application logs

For applications with log levels, timestamps, destinations, and error reporting, use the logging module rather than scattered print() calls:

import logging

logging.basicConfig(level=logging.INFO)
logging.info("Backup started")

Logging handlers manage output consistently and are easier to configure in real projects.

Keep input prompts visible

When writing directly to standard output before reading input, flush first:

import sys

sys.stdout.write("Enter your name: ")
sys.stdout.flush()
name = input()

input("Enter your name: ") is usually simpler when an ordinary prompt is all you need.

Common Mistakes

Assuming a newline always solves buffering

A newline often causes output to appear promptly in an interactive terminal, but this is not guaranteed when output is redirected to a file or piped to another program.

print("Working...")  # May still be buffered in some destinations

Use flush=True when the timing is important:

print("Working...", flush=True)

Putting flush in the wrong place

flush is a keyword argument to print(), not an argument to the string.

# Incorrect
print("Working...", "flush=True")
# Correct
print("Working...", flush=True)

Forgetting to flush when omitting the newline

This is common with progress output:

# May not appear immediately
print("Loading", end="")

Use:

print("Loading", end="", flush=True)

Calling flush() on the result of print()

print() returns None, so this does not work:

# Incorrect
print("Working...").flush()

Flush the stream instead:

import sys

print("Working...")
sys.stdout.flush()

Confusing flushing with saving a file permanently

Flushing moves Python's buffered data to the underlying stream. It is not the same as forcing all data to stable storage. For ordinary text output, flush() is normally the appropriate operation; file durability requirements may need additional operating-system-specific handling.

Comparisons

ApproachBest useExampleNotes
print(..., flush=True)Flush one print callprint("Ready", flush=True)Most readable choice for a single message.
sys.stdout.flush()Flush after multiple writessys.stdout.flush()Requires import sys.
file.flush()Flush a specific open filelog_file.flush()Useful when writing directly with write().
Newline (\n)Normal terminal outputprint("Ready")Often appears immediately in a terminal, but do not rely on it for every destination.
python -uChange buffering for the whole processpython -u script.pyUseful when process-wide unbuffered output is required, not just one call.

flush=True affects the output stream used by that print() call. For example, print("x", file=my_file, flush=True) flushes my_file, not necessarily sys.stdout.

Take Quiz

Cheat Sheet

# Flush one print call
print("Message", flush=True)

# Important when not ending with a newline
print("Loading...", end="", flush=True)

# Flush standard output manually
import sys
print("Message")
sys.stdout.flush()

# Flush a file after printing to it
print("Saved", file=log_file, flush=True)

# Flush after direct writes
sys.stdout.write("Message")
sys.stdout.flush()
  • flush defaults to False.
  • Use flush=True when output must be sent onward before slow work starts.
  • A newline may flush output in an interactive terminal, but redirected output can remain buffered.
  • Use end="" or end="\r" with flush=True for live progress output.
  • Use logging rather than print() for structured application logging.

FAQ

How do I flush print() output in Python?

Pass flush=True:

print("Message", flush=True)

What does flush=True do in Python?

It tells the output stream to flush buffered data immediately after print() writes its text.

Why does Python output appear late when redirected to a file or pipe?

The output stream may use block buffering rather than interactive terminal behavior. Explicitly use flush=True when a particular message must be sent immediately.

Do I need flush=True after every print() call?

Usually no. Use it for progress messages, prompts, diagnostics, and output that must appear before a delay or long-running operation.

Is print(..., flush=True) the same as sys.stdout.flush()?

For the default standard output stream, it has a similar effect after that one print call. sys.stdout.flush() is more flexible when you have made several writes or need to control the flush separately.

Does print() automatically flush when it prints a newline?

It often does when writing to an interactive terminal, but the exact behavior depends on the stream and environment. Pipes and redirected files may still buffer output.

Can I flush output written to a file?

Yes. Call the file object's flush() method, or use print(..., file=your_file, flush=True).

Take Quiz

Mini Project

Description

Build a small command-line task runner that reports each stage as it begins. The task runner uses flushed output so users see status updates immediately, even while each simulated task is still running.

Goal

Display live task status messages and a percentage progress indicator using print(..., flush=True).

Requirements

Create a list of at least three task names. Print a status message before each task starts. Pause briefly to simulate work. Show progress on one updating terminal line. Flush every status or progress update that must appear immediately.

Take Quiz

Keep learning

Related questions

View more