如何在 Python 中打印到 stderr? [英] How to print to stderr in Python?

查看:32
本文介绍了如何在 Python 中打印到 stderr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有几种写入标准错误的方法:

# 注意:第一个在 Python 3 中不起作用打印 >>sys.stderr,垃圾邮件"sys.stderr.write("垃圾邮件
")os.write(2, b"垃圾邮件
")从 __future__ 导入 print_function打印(垃圾邮件",文件=sys.stderr)

这似乎与 zen of Python #13 相矛盾,那么这里有什么区别?其中一种方式有什么优点或缺点?应该用哪种方式?

应该有一种——最好只有一种——显而易见的方法.

解决方案

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

#这行只有你还关心Python2从 __future__ 导入 print_function导入系统def eprint(*args, **kwargs):打印(*args,文件=sys.stderr,**kwargs)

可选功能eprint 节省了一些重复.它可以像标准的print函数一样使用:

<预><代码>>>>打印(测试")测试>>>eprint(测试")测试>>>eprint("foo", "bar", "baz", sep="---")foo---bar---baz

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
")

os.write(2, b"spam
")

from __future__ import print_function
print("spam", file=sys.stderr)

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?

There should be one — and preferably only one — obvious way to do it.

解决方案

I found this to be the only one short, flexible, portable and readable:

# 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)

The optional function eprint saves some repetition. It 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆