如何在Python中打印到stderr? [英] How to print to stderr in Python?
本文介绍了如何在Python中打印到stderr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有几种写stderr的方法:
There are 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)
这似乎与python#13的 zen †相矛盾,所以这里有什么区别,一种方法或另一种方法有什么优点或缺点?应该使用哪种方式?
That seems to contradict zen of Python #13 †, so what's the difference here and are there any advantages or disadvantages to one way or the other? Which way should be used?
† 应该有一种明显的方法,最好只有一种.
推荐答案
我发现这是唯一的一个简短+灵活+可移植+可读的
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)
功能eprint
的使用方式与标准print
功能相同:
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
这篇关于如何在Python中打印到stderr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文