printing – How to print to stderr in Python?

printing – How to print to stderr in Python?

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

# This line only if you still care about Python2
from __future__ import print_function

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)
>>> eprint(Test)
>>> eprint(foo, bar, baz, sep=---)
import sys

Is my choice, just more readable and saying exactly what you intend to do and portable across versions.

Edit: being pythonic is a third thought to me over readability and performance… with these two things in mind, with python 80% of your code will be pythonic. list comprehension being the big thing that isnt used as often (readability).

printing – How to print to stderr in Python?

Python 2:

print >> sys.stderr, fatal error

Python 3:

print(fatal error, file=sys.stderr)

Long answer

print >> sys.stderr is gone in Python3. says:

Old: print >> sys.stderr, fatal error
New: print(fatal error, file=sys.stderr)

For many of us, it feels somewhat unnatural to relegate the destination to the end of the command. The alternative

sys.stderr.write(fatal errorn)

looks more object oriented, and elegantly goes from the generic to the specific. But note that write is not a 1:1 replacement for print.

Leave a Reply

Your email address will not be published. Required fields are marked *