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 via str(), separates multiple arguments with spaces (sep=" "), appends a newline (end="\n"), and accepts flush=True—whereas sys.stderr.write() accepts only a str, does not append \n automatically, and raises TypeError: write() argument must be str, not int if passed an integer or exception object directly.
  • Line buffering vs. block buffering when piping or redirecting stderr (2> error.log):
    • When attached to an interactive terminal (TTY), sys.stderr is line-buffered (flushes on \n), but when redirected to a file or pipe in a background daemon/Docker container, sys.stderr becomes block-buffered unless you pass flush=True (print("Fatal error", file=sys.stderr, flush=True)) or run Python with python -u.
  • Keep stdout clean for machine-readable data (JSON, CSV, piped output):
    • Writing errors and progress messages to sys.stderr prevents breaking downstream shell pipelines such as python export.py | jq . or python dump.py > data.csv, where stdout must contain strictly valid data while diagnostics appear in the terminal or 2> err.log.
  • 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 to sys.stderr and exits the process with exit code 1 in a single step.
  • Avoid os.write(2, ...) unless inside a low-level signal handler or post-fork() child:
    • File descriptor 2 is the OS-level stderr, but os.write(2, b"...") bypasses Python’s sys.stderr wrapper (breaking pytest’s capsys capture and contextlib.redirect_stderr()).

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.