Pass file=sys.stderr to Python’s built-in print() function (print("Error: invalid config", file=sys.stderr)) for quick CLI diagnostics, or use the standard library logging module (logging.error("..."), which writes to sys.stderr by default) for structured severity levels, timestamps, and file/stream routing in applications.
Basic Example
import logging
import sys
# 1. Recommended for CLI scripts: Pass `file=sys.stderr` directly to print()
print("Error: configuration file not found.", file=sys.stderr)
# 2. Recommended for applications/libraries: `logging` writes to `sys.stderr` by default
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logging.error("Database connection timed out after 5s.")
# 3. Direct low-level stream write (requires manual trailing "\n" and str conversion):
sys.stderr.write("Fatal: aborting worker process.\n")
sys.stderr.flush()
Key Details & Edge Cases
print(..., file=sys.stderr)vs.sys.stderr.write(...):print(..., file=sys.stderr)automatically converts non-string arguments viastr(), separates multiple arguments with spaces (sep=" "), appends a newline (end="\n"), and acceptsflush=True—whereassys.stderr.write()accepts only astr, does not append\nautomatically, and raisesTypeError: write() argument must be str, not intif passed an integer or exception object directly.
- Line buffering vs. block buffering when piping or redirecting
stderr(error.log):- When attached to an interactive terminal (TTY),
sys.stderris line-buffered (flushes on\n), but when redirected to a file or pipe in a background daemon/Docker container,sys.stderrbecomes block-buffered unless you passflush=True(print("Fatal error", file=sys.stderr, flush=True)) or run Python withpython -u.
- When attached to an interactive terminal (TTY),
- Keep
stdoutclean for machine-readable data (JSON,CSV, piped output):- Writing errors and progress messages to
sys.stderrprevents breaking downstream shell pipelines such aspython export.py | jq .orpython dump.py > data.csv, wherestdoutmust contain strictly valid data while diagnostics appear in the terminal orerr.log.
- Writing errors and progress messages to
- Exiting with a non-zero status code alongside an error message (
sys.exit(...)):- Passing a string directly to
sys.exit("Error: missing API key")prints that string tosys.stderrand exits the process with exit code1in a single step.
- Passing a string directly to
- Avoid
os.write(2, ...)unless inside a low-level signal handler or post-fork()child:- File descriptor
2is the OS-levelstderr, butos.write(2, b"...")bypasses Python’ssys.stderrwrapper (breakingpytest’scapsyscapture andcontextlib.redirect_()).
- File descriptor
Comparison of Methods for Writing Errors to stderr in Python
| Method | Auto-Appends \n? |
Accepts Any Object (int, Exception)? |
Supports flush=True & pytest capsys? |
Best Used When |
|---|---|---|---|---|
print("...", file=sys.stderr) (Recommended) |
Yes | Yes (calls str() automatically) |
Yes | CLI scripts, quick error diagnostics, and keeping stdout clean for piped data. |
logging.error("...") (Recommended for apps) |
Yes | Yes (supports %s formatting & exc_info=True) |
Yes (defaults to StreamHandler(sys.stderr)) |
Production apps and libraries needing log levels (WARNING, ERROR), timestamps, and stack traces. |
sys.stderr.write("...\n") |
No (manual \n) |
No (str only; TypeError otherwise) |
Yes (call .flush() manually) |
High-throughput streaming output where you control exact chunk boundaries and newlines. |
sys.exit("Error message") |
Yes | Yes | Yes (writes to sys.stderr + exits with code 1) |
Fatal CLI startup errors where the script should immediately abort with a non-zero exit code. |
You must log in or register to comment.