Print to standard error in Python

Send diagnostics to stderr with print or logging, keep them separate from stdout, and redirect each stream independently.

Best practices
Python programming and application logging

Use print(message, file=sys.stderr) for a simple diagnostic. This keeps errors and warnings separate from normal output on sys.stdout, which is useful when another program consumes your script's output.

Print a diagnostic

import sys

print("Unable to read the configuration", file=sys.stderr)

print appends a newline by default. Add flush=True if you need it to flush the stream immediately.

For lower-level writing, supply the newline yourself:

import sys

sys.stderr.write("Unable to read the configuration\n")

Neither method automatically terminates the process or changes its exit status. Use explicit error handling when a failure should stop the script.

Use logging for application events

import logging

logging.basicConfig(level=logging.WARNING)
logging.error("Unable to read the configuration")

In a fresh script, basicConfig creates a stream handler that writes to stderr unless another destination is specified. If handlers already exist, basicConfig normally leaves them in place; frameworks may configure different destinations. Logging adds levels and formatting and is usually a better fit for recurring application diagnostics.

Redirect the streams separately

In a POSIX shell:

# Save diagnostics while leaving standard output in the terminal.
python3 script.py 2> error.log

# Save normal output while leaving diagnostics in the terminal.
python3 script.py > output.log

# Pipe normal output to the next command.
python3 script.py | grep pattern

The last pipeline does not include stderr unless you explicitly redirect it. Use > combined.log 2>&1 when both streams should go to one file; redirection order matters.

FAQ

Do the streams look different in a terminal? Usually not. They are separate destinations even when both appear in the same terminal window.

Do they have identical performance? There is no such guarantee. Buffering, flushing, destination speed, and write frequency all affect cost. Avoid high-frequency diagnostic output in a hot loop unless you have measured its impact.

Where does stderr appear in a notebook? Typically in the cell's output area. Styling depends on the notebook frontend and theme; a red background is not a portable property of stderr.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting