How to print to stderr and stdout in Python

avatar

Borislav Hadzhiev

Last updated: Sep 5, 2022

banner

Photo from Unsplash

How to print to stderr and stdout in Python #

By default, the print() function prints to stdout. To print to stderr, set the file keyword argument to sys.stderr in the call to the print() function, e.g. print("an error occurred", file=sys.stderr).

main.py
import sys # 👇️ prints to stderr print("an error occurred", file=sys.stderr) # 👇️ prints to stdout print('example')

The print function takes one or more objects and prints them to sys.stdout.

stdout is used for the output of the print() function and for the prompts of input().

stderr is used for the interpreter's prompts and error messages.

By default, the file keyword argument is set to the current value of sys.stdout.

If you run the code snippet, you will see both messages printed to your terminal. This is the default behavior.

stderr and stdout

Having stdout and stderr separately is useful because one of them can be redirected to a file, a buffer or /dev/null while the other one can be kept pointing to the terminal.

main.py
from io import StringIO import sys buffer = StringIO() # 👇️ redirect sys.stdout (messages won't be shown to terminal) sys.stdout = buffer print('⛔️ This is NOT shown') print('✅ This is shown', file=sys.stderr)

redirect stdout keep stderr

The file keyword argument of the print() function defaults to sys.stdout.

We redirected sys.stdout to an in-memory buffer so print() isn't connected to the terminal when the file keyword argument is not specified.

However, sys.stderr still points to the terminal, so the message of the second print() class is shown.

Something you might commonly have to do is redirect the output of the print() function to a variable while still being able to use sys.stderr to print to the terminal.

main.py
from io import StringIO import sys # 👇️ redirect sys.stdout to buffer buffer = StringIO() sys.stdout = buffer # 👇️ store output of print() in a variable print('Store this in the variable below ✅') print_output = buffer.getvalue() print('Can still use stderr', file=sys.stderr) # 👉️ Can still use stderr # 👇️ restore stdout to default for print (optional) sys.stdout = sys.__stdout__ # 👇️ -> Store this in the variable below ✅ print('->', print_output)

store print output in variable

The io.StringIO class returns an in-memory buffer.

We redirected sys.stdout to the buffer and used the print() function to print a value.

The value can be accessed with the getvalue() method.

The method returns a bytes object that contains the entire contents of the buffer.

After the value is stored in a variable, you can restore the sys.stdout attribute to the default, so you can use the print() function.

Even when sys.stdout is redirected, we can still use the print() function with the file keyword argument set to sys.stderr to print to the terminal.

An alternative and perhaps cleaner approach is to use the logging module to log to sys.stderr.

main.py
import logging FORMAT = '%(message)s' logging.basicConfig(format=FORMAT) # 👇️ __name__ is module's name logger = logging.getLogger(__name__) logger.warning('prints to stderr') print('prints to stdout')

logging stderr and stdout

We used the logging.basicConfig method to initialize the basic configuration for the logger.

The %(message)s format simply includes the message in the logging call.

The logging.getLogger method returns the logger with the specified name.

The __name__ global variable stores the module's name.

The logger.warning() method prints to sys.stderr by default and the print() function prints to sys.stdout by default.

This is because by default, the stream keyword argument of the basicConfig method is set to sys.stderr, whereas the file argument in the print() function is set to sys.stdout .

main.py
import sys import logging FORMAT = '%(message)s' # 👇️ specified default value for stream logging.basicConfig(stream=sys.stderr, format=FORMAT) # 👇️ __name__ is module's name logger = logging.getLogger(__name__) logger.warning('prints to stderr') # 👇️ specified default value for file print('prints to stdout', file=sys.stdout)
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.