Python – How to print to stderr in Python


There are several ways to write to stderr:

# Note: this first one does not work in Python 3
print >> sys.stderr, "spam"


os.write(2, b"spam\n")

from __future__ import print_function
print("spam", file=sys.stderr)

That seems to contradict zen of Python #13 , so what's the difference here and are there any advantages or disadvantages to one way or the other? Which way should be used?

There should be one — and preferably only one — obvious way to do it.

Best Solution

I found this to be the only one short, flexible, portable and readable:

from __future__ import print_function
import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

The function eprint can be used in the same way as the standard print function:

>>> print("Test")
>>> eprint("Test")
>>> eprint("foo", "bar", "baz", sep="---")