How to Print to stderr in Python (With Examples)

When developing Python scripts of any kind, including automation scripts or command-line tools, it is vital to differentiate between standard output and error messages. This is where stderr (Standard Error) comes in. While normal output is printed using stdout, error reporting and diagnostics information is sent to separate stderr.

This guide will provide you with straightforward examples so you can learn how to print to stderr in Python right away.

Print to stderr in Python – Examples

You can send messages to the error stream (stderr) instead of the standard output. This is useful for logging errors without mixing them with standard output.

Using print() with file=sys.stderr

import sys


print("This is an error message", file=sys.stderr)

This works just like a regular print(), but the message goes to stderr.

Using sys.stderr.write()

import sys


sys.stderr.write("This is another error message")

Both methods send output to the same place stderr, but print(…, file=sys.stderr) is usually simple & best for everyday use.

Want to understand what stderr actually is?
If you’re curious about why and how stderr works behind the scenes, keep reading this section for a quick explanation.

What is stderr in Python?

There are three standard streams in Python through which the program interacts with its environment:

  1. stdin – Standard Input (the keyboard as default).
  2. stdout – Standard Output (usually the output of the program).
  3. stderr  – Standard Error (contains error messages and diagnostic messages).

Error messages are output to the stderr stream and as mentioned above, result codes are output to the stdout stream. Both stdout and stderr, by default, display texts in the console. Their purpose varies; stdout captures ‘normal output’ while stderr captures ‘error output’ thus enabling one to separate output messages from error messages and allowing me to manipulate or filter the script output independently. The independent manipulation of output messages and errors aids greatly when running scripts as part of larger workflows or pipelines.

To illustrate, If you are analyzing datasets while writing outputs into files, but you want error messages to show up on the screen, then the use of a stderr stream helps achieve that while error messages can be logged separately.

Leave a Comment