How to print to stderr in Python?
I found this to be the only one short, flexible, portable and readable:
from __future__ import print_functionimport sysdef 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")Test>>> eprint("Test")Test>>> eprint("foo", "bar", "baz", sep="---")foo---bar---baz
import syssys.stderr.write()
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 isn't used as often (readability).
Python 2:
print >> sys.stderr, "fatal error"
Python 3:
print("fatal error", file=sys.stderr)
Long answer
print >> sys.stderr
is gone in Python3.http://docs.python.org/3.0/whatsnew/3.0.html 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 error\n")
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
.