Print to stderr in Python

The tutorial will cover how to print stderr errors in two different ways in Python 2.x and 3.x.

 

The print() function in 3.x accepts a file argument, which defaults to sys.stout. To print an error, change the value of file to sys.stderr like this:

 

import sys

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

 

To print errors in Python 2.x, use the file-like destination operator (>>) and supply sys.stderr followed by the error message like this:

 

import sys

print >> sys.stderr, "Error"
Error

Another way to print an stderr in Python is using the sys.stderr.write() method. Supply the error message to display as the first argument like this:

 

import sys

sys.stderr.write("Error")
Error