Question
In Python, there are several ways to write output to standard error (stderr):
# Python 2 only
print >> sys.stderr, "spam"
sys.stderr.write("spam\n")
os.write(2, b"spam\n")
from __future__ import print_function
print("spam", file=sys.stderr)
What are the differences between these approaches, and which one should generally be preferred when writing to stderr?
Short Answer
By the end of this page, you will understand what stderr is, how it differs from normal output, and how Python writes to it using print(), sys.stderr.write(), and os.write(). You will also learn when each option is appropriate and which one is usually the best choice in everyday Python code.
Concept
stderr stands for standard error. It is one of the three standard streams available to most programs:
stdinfor inputstdoutfor normal outputstderrfor error messages and diagnostics
Using stderr matters because it keeps error messages separate from normal program output. This is especially useful when:
- piping output into another program
- saving output to a file
- logging failures while still returning usable data on
stdout
In Python, there are multiple ways to write to stderr, but they operate at different levels:
print(..., file=sys.stderr)is the high-level, readable waysys.stderr.write(...)writes directly to Python's error stream objectos.write(2, ...)writes directly to the operating system file descriptor forstderr
These methods differ in:
- abstraction level
- type of data expected (
strvsbytes)
Mental Model
Think of your program as having two speakers:
- one speaker talks to the user normally:
stdout - the other speaker is reserved for problems and warnings:
stderr
Now think of the writing methods as different ways of speaking:
print(..., file=sys.stderr)is like speaking naturally and letting Python handle formattingsys.stderr.write(...)is like writing a note directly onto the error channel yourselfos.write(2, ...)is like bypassing Python's front desk and handing a raw message straight to the operating system
Most of the time, you want the convenient and clear option. Only use the lower-level option when you specifically need lower-level control.
Syntax and Examples
The most common ways to write to stderr in modern Python are:
import sys
print("Something went wrong", file=sys.stderr)
sys.stderr.write("Something went wrong\n")
Using print()
import sys
print("Invalid input", file=sys.stderr)
What it does:
- writes text to
stderr - automatically converts values to text
- automatically adds a newline unless changed with
end - supports
sep,end, andflush
Example:
import sys
name = "Sam"
count = 3
print("Warning:", name, "has", count, "failed attempts", file=sys.stderr)
This is convenient because print() handles spacing and conversion for you.
Step by Step Execution
Consider this example:
import sys
print("Start", file=sys.stderr)
sys.stderr.write("Loading...\n")
print("Done", file=sys.stderr)
Step by step
-
import sys- Imports the
sysmodule so we can accesssys.stderr.
- Imports the
-
print("Start", file=sys.stderr)print()sends the textStarttostderr.- It automatically adds a newline.
stderrnow receives:
Start -
sys.stderr.write("Loading...\n")- Writes the exact string to
stderr. - The newline is included manually.
stderrnow also receives:
- Writes the exact string to
Real World Use Cases
Writing to stderr is common in many real programs.
Command-line tools
A CLI tool may output useful data to stdout and errors to stderr:
import sys
filename = "missing.txt"
print(f"Could not open {filename}", file=sys.stderr)
This keeps error messages separate from normal program results.
Data processing scripts
If a script prints CSV or JSON to stdout, warnings should go to stderr so they do not corrupt the data stream.
import sys
import json
print(json.dumps({"status": "ok"}))
print("Warning: partial data used", file=sys.stderr)
Validation and user feedback
Programs often report invalid user input through stderr:
import sys
age = -
age < :
(, file=sys.stderr)
Real Codebase Usage
In real Python codebases, developers usually use print(..., file=sys.stderr) for simple messages and logging for structured application logs.
Common pattern: simple CLI errors
import sys
if len(sys.argv) < 2:
print("Usage: script.py <filename>", file=sys.stderr)
raise SystemExit(1)
This is common because it is readable and easy to understand.
Common pattern: guard clauses
import sys
def divide(a, b):
if b == 0:
print("Error: division by zero", file=sys.stderr)
return None
return a / b
The error is reported early, and the function exits safely.
Common pattern: validation
import sys
def validate_username(username):
if username:
(, file=sys.stderr)
Common Mistakes
1. Forgetting the newline with sys.stderr.write()
Broken code:
import sys
sys.stderr.write("Error happened")
sys.stderr.write("Try again")
Output:
Error happenedTry again
Fix:
import sys
sys.stderr.write("Error happened\n")
sys.stderr.write("Try again\n")
2. Using os.write() with a normal string
Broken code:
import os
os.write(2, "spam\n")
In Python 3, os.write() expects bytes, not str.
Fix:
import os
os.write(2, b"spam\n")
3. Writing errors to by accident
Comparisons
| Method | Python Version | Input Type | Adds Newline Automatically | Level | Typical Use |
|---|---|---|---|---|---|
print(..., file=sys.stderr) | Python 3 | str and printable values | Yes | High-level | Best general-purpose choice |
sys.stderr.write(...) | Python 2 and 3 | str | No | Medium-level | Exact text control |
os.write(2, ...) | Python 2 and 3 | bytes | No |
Cheat Sheet
import sys
import os
Write to stderr
print("message", file=sys.stderr)
sys.stderr.write("message\n")
os.write(2, b"message\n")
Quick rules
-
print(..., file=sys.stderr)- best default choice
- adds newline automatically
- accepts multiple values
-
sys.stderr.write(...)- writes exact string
- no automatic newline
- use
\nmanually
-
os.write(2, ...)- writes to file descriptor
2 - expects
bytes - low-level, uncommon in regular Python apps
- writes to file descriptor
Good default
import sys
(, file=sys.stderr)
FAQ
What is the best way to print to stderr in Python?
In modern Python, print("message", file=sys.stderr) is usually the best choice because it is readable and idiomatic.
Should I use sys.stderr.write() or print()?
Use print() for most cases. Use sys.stderr.write() when you need exact control over formatting and do not want print() to add a newline automatically.
Why does os.write() use bytes instead of strings?
Because os.write() works at the operating system level and writes raw bytes directly to a file descriptor.
Is print >> sys.stderr valid in Python 3?
No. That syntax is only for Python 2.
Does print(..., file=sys.stderr) automatically add a newline?
Yes. Like normal print(), it adds a newline unless you change the end argument.
When should I use the logging module instead of stderr printing?
Mini Project
Description
Build a small command-line validation script that reads a filename from the user, reports problems to stderr, and prints successful results to stdout. This demonstrates why separating normal output from error output is useful in real scripts.
Goal
Create a Python script that prints valid success information to stdout and sends error messages to stderr using the recommended modern approach.
Requirements
- Accept a filename variable in the script.
- If the filename is empty, print an error to
stderrand stop. - If the filename does not end with
.txt, print a warning tostderr. - If the filename is valid, print a success message to
stdout. - Use
print(..., file=sys.stderr)for error or warning output.
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.
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.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.