HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How do I print to stderr in Python?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
printstderrhowpython

Problem

There are several ways to write to stderr:

print >> sys.stderr, "spam"  # Python 2 only.

sys.stderr.write("spam\n")

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

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


What are the differences between these methods? Which method should be preferred?

Solution

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

import sys

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


The optional function eprint saves some repetition. It can be used in the same way as the standard print function:

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

Code Snippets

import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)
>>> print("Test")
Test
>>> eprint("Test")
Test
>>> eprint("foo", "bar", "baz", sep="---")
foo---bar---baz

Context

Stack Overflow Q#5574702, score: 1648

Revisions (0)

No revisions yet.