Back to articles list Articles
4 minutes read

How to Print to the Standard Error Stream in Python

Printing to Python’s standard error stream will help you better manage handling any errors in your programs. Find out how to do it in this article.

Standard streams allow a program to interact with its environment during execution. This could be accepting input from the keyboard (using the input() function in Python), or displaying a message on the screen (using the print() function). There are three standard streams in computing: standard input, standard output, and standard error; they are commonly referred to as stdin, stdout, and stderr, respectively. The sys module allows you to access these streams in Python.

For those of you who are new to Python, our Python Basics course uses interactive exercises to teach you the fundamentals of computer programming. Or check out the Learn Programming with Python track, which bundles several beginner-friendly courses. Following either of these paths will help you learn Python faster.

What Is Python’s Standard Error Stream?

Standard error is an output stream which can be printed to the screen or redirected to a log file. This means any error messages can be analyzed to understand the cause of any bugs. It is independent of the standard output and can be redirected separately.

There are several ways to print to standard error in Python. We will discuss them below, giving you another tool to help you think like a Python developer.

3 Ways to Print to the Standard Error Stream in Python

1.   Print to stderr Using print()

The first method to print to standard error is to use the built-in print() function. We have an article describing all you need to know about Python’s print() function; you can refer to it for additional details. For now, here’s an example of using print():

>>> import sys
>>> print('Error message', file=sys.stderr)

This is the output:

Error message

Here we used the optional argument file to redirect the output to standard error. By default, the output from the print() function would be directed to standard output. If you want to save a little bit of typing, you can define your own function:

>>> def print_error(*args, **kwargs):
... 	print(*args, file=sys.stderr, **kwargs)

Then you can run the function as follows:

>>> print_error('Error message')

This is the output:

Error message

You can also specify additional keyword arguments to give to the print() statement. The end keyword allows you to define what gets printed at the end of the output:

>>> print_error('Error message', end=', good luck debugging me!')

Now this is the output:

Error message, good luck debugging me!

2.   Printing to stderr Using sys.stderr.write()

The second common method to print to standard error in Python doesn’t rely on the print() function; it uses sys.stderr.write(). Here’s an example:

>>> sys.stderr.write('Error message\n')

This is the output:

Error message
Out[1]: 14

The function displays the error message and returns an integer.  Returning the integer only occurs when the function is executed in the interactive Python console; it represents the length of the string.  The newline character ('\n') counts as one character, and is included here because sys.stderr.write() doesn’t move to a new line after displaying the text.

3.   Printing to stderr Using logging

The last method uses the logging module, which has functions to help you log events during your programs’ execution.  By default, this module prints messages to standard error.  You can import the library and log a warning as follows:

>>> import logging
>>> logging.basicConfig(format='%(message)s')
>>> log = logging.getLogger(__name__)
>>> log.warning('Error message')

Here we configure the format of the output, instantiate a logger object with the variable __name__, and log a warning. This is the output:

Error message

This logs the error message with level WARNING. There are other functions which allow you to log errors at different levels and have much more functionality. Check out Python’s documentation for more details.

Use Python’s Standard Error Stream to Work Smarter

In this article, we presented several methods to print to Python’s standard error stream. Remember, this stream is independent of standard output. By taking advantage of the standard error stream, you will ensure there’s little chance of your program crashing before errors are logged – which is a dangerous way for your programs to end. Logging errors properly makes debugging programs easier.