如何在 Python 中打印到 stderr?
发布于 2022-03-22 23:30:44
有几种方法可以写入 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 相矛盾,那么这里有什么区别,一种或另一种方式有什么优点或缺点吗?应该使用哪种方式?
关注者
0
被浏览
83
1 个回答
-
我发现这是唯一一个简短、灵活、便携和可读的:
# 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)
可选功能
eprint
节省了一些重复。它可以像标准print
函数一样使用:>>> print("Test") Test >>> eprint("Test") Test >>> eprint("foo", "bar", "baz", sep="---") foo---bar---baz