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.
Print to stderr
in Python 3.x
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 )
Output:
Error
Print to stderr
in Python 2.x
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!"
Output:
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
sys.stderr.write("Error!")
Output:
Error!
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!')
Output:
Error Found!
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.
LinkedIn