How to print to stderr in Python?
I've come across at least three ways to print to stderr:
import sys
print >> sys.stderr, 'spam'
sys.stderr.write('spamn')
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.
I found this to be the only one short + flexible + portable + 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")
Test
>>> eprint("Test")
Test
>>> eprint("foo", "bar", "baz", sep="---")
foo---bar---baz
sys.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).
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'}))
上一篇: Safari CSS字体颜色问题
下一篇: 如何在Python中打印stderr?