Python - How To Print to stderr in Python

ID : 151

viewed : 82

Tags : PythonPython Print

vote vote

93

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 ) 

Output:

Error 

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 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! 

  • Related HOW TO?