How to print to stderr in Python
In order to have Python print to stderr
, we'll need to point the print
function to the sys.stderr
file. It's done slightly differently in Python 3 compared to Python 2.
Python 3
import sys
print('Hello world', file=sys.stderr)
In Python3, print
is a function and takes the output file as an argument. We can use it to print to any file, and in this case it's sys.stderr
.
Python 2
In Python 2, we can use the print >> sys.stderr
syntax, which has been deprecated in Python 3, since in Python 3 print
is a function instead of a statement.
import sys
print >> sys.stderr, 'Hello world'
Other methods
Of course, since sys.stderr
is a file object in both Python 2 and Python 3, we can use the write()
method.
import sys
sys.stderr.write('Hello world')
Just be mindful that file.write()
doesn't automatically add a newline at the end of each write call like print
does, so you might want to append a \n
to your output explicitly.