如何在 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 个回答
  • 面试哥
    面试哥 2022-03-22
    为面试而生,有面试问题,就找面试哥。

    我发现这是唯一一个简短、灵活、便携和可读的:

    # 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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看