Question
Flush Print Output in Python: print() Buffering and flush=True
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=Trueis 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.
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=)
(, end=)
sys.stdout.flush()
Step by Step Execution
Consider this program:
import time
print("Preparing report...", flush=True)
time.sleep(3)
print("Report complete.")
Execution trace:
- Python imports the
timemodule. print("Preparing report...", flush=True)writes the message to standard output.- Because
flush=Trueis set, Python immediately flushessys.stdout. - The user can see
Preparing report...before the next line runs. time.sleep(3)pauses the program for three seconds.- 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. ")
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:
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:
Comparisons
| Approach | Best use | Example | Notes |
|---|---|---|---|
print(..., flush=True) | Flush one print call | print("Ready", flush=True) | Most readable choice for a single message. |
sys.stdout.flush() | Flush after multiple writes | sys.stdout.flush() | Requires import sys. |
file.flush() | Flush a specific open file | log_file.flush() | Useful when writing directly with write(). |
Newline (\n) | Normal terminal output |
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()
flushdefaults toFalse.- Use
flush=Truewhen 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=""orend="\r"withflush=Truefor live progress output. - Use
loggingrather thanprint()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 automatically flush when it prints a newline?
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.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.