I've come across several ways to write to stderr:
# Note: this first one does not work in Python 3
print >> sys.stderr, "spam"
sys.stderr.write("spam\n")
os.write(2, b"spam\n")
from __future__ import print_function
print("spam", file=sys.stderr)
It seems to contradict zen of Python #13 †, so what's the preferred way to do it? Are there any advantages or disadvantages to one way or the other?
† There should be one — and preferably only one — obvious way to do it.
If you do a simple test:
You will find that sys.stderr.write() is consistently 1.81 times faster!
I found this to be the only one short + flexible + portable + readable:
The function
eprint
can be used in the same way as the standardprint
function:print >> sys.stderr
is gone in Python3. http://docs.python.org/3.0/whatsnew/3.0.html says:Unfortunately, this is quite ugly. Alternatively, use
but note that
write
is not a 1:1 replacement forprint
.I did the following using Python 3:
So now I'm able to add keyword arguments, for example, to avoid carriage return:
Try:
For Python 2 my choice is:
print >> sys.stderr, 'spam'
Because you can simply print lists/dicts etc. without convert it to string.print >> sys.stderr, {'spam': 'spam'}
instead of:sys.stderr.write(str({'spam': 'spam'}))