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.
Print to stderr in Python 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 |
Print to stderr in Python 2.x
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 |
Print stderr Using the sys.stderr.write() Method
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 |