小编典典

如何在 Python 中打印到 stderr?

python

有几种方法可以写入 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 相矛盾,那么这里有什么区别,一种或另一种方式有什么优点或缺点吗?应该使用哪种方式?


阅读 319

收藏
2022-02-21

共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
2022-02-21