Print to stderr in Python

Syed Moiz Haider Dec 10, 2020 Nov 09, 2020 Python Python Print
  1. Print to stderr in Python 2.x
  2. Use logging Module to Print to stderr
Print to stderr in Python

This tutorial explains how to write to the standard error output, stderr, in Python. It also lists some example codes to explain different ways to write to stderr as the syntax has changed over time.

For Python3.x, the print function has a keyword argument file that specifies the printing destination. It is sys.stdout by default but could be sys.stderr or even a file path.

It prints the message to stderr if file=sys.stderr. An example code is given below:

import sys

print("Error", file = sys.stderr )



For Python2.x, the print statement could print the message to a file-like destination like stdout, stderr, or a file path. This file-like object is specified after the >>. See the below example.

import sys

print >> sys.stderr, "Error Detected!"


Error Detected!

Use the sys.stderr to Print to stderr

The sys module of Python provides valuable information and key functionalities. sys.stderr.write() method can be used. sys.stderr.write() method prints the message as the given parameter to the stderr. See the example below.

import sys




Use logging Module to Print to stderr

The logging module in Python is specifically created to log messages. Logging module can be used to print to stderr after setting the basic configuration. logging.basicConfig() takes the format of message as its input, and logging.getLogger() returns an object of the logging. The log.warning() takes the warning text and prints it to stderr.

A basic example of this approach is shown below:

import logging

logging.basicConfig(format = '%(messages)s')
log = logging.getLogger()

log.warning('Error Found!')


Error Found!
Syed Moiz Haider avatar Syed Moiz Haider avatar

Syed Moiz is an experienced and versatile technical content creator. He is a computer scientist by profession. Having a sound grip on technical areas of programming languages, he is actively contributing to solving programming problems and training fledglings.


Related Article - Python Print

  • Print Multiple Arguments in Python
  • Print With Column Alignment in Python
  • Print Subscripts to the Console Window in Python
  • Print Quotes in Python
  • Fix Missing Parentheses in Print Error in Python
  • Print % Sign in Python