如何在 Python 中打印到 stderr?
写入 stderr 的方法有多种:
print >> sys.stderr, "spam" # Python 2 only.
sys.stderr.write("spam\n")
os.write(2, b"spam\n")
from __future__ import print_function
print("spam", file=sys.stderr)
这些方法之间有什么区别?应该首选哪种方法?
There are several ways to write to stderr:
print >> sys.stderr, "spam" # Python 2 only.
sys.stderr.write("spam\n")
os.write(2, b"spam\n")
from __future__ import print_function
print("spam", file=sys.stderr)
What are the differences between these methods? Which method should be preferred?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
我发现这是唯一一个简短、灵活、可移植且可读的函数:
可选函数
eprint
可以节省一些重复。它的使用方式与标准print
函数相同:I found this to be the only one short, flexible, portable and readable:
The optional function
eprint
saves some repetition. It can be used in the same way as the standardprint
function:是我的选择,只是更具可读性,更准确地说出您打算做什么,并且可以跨版本移植。
编辑:对我来说,“Pythonic”是关于可读性和性能的第三个想法……考虑到这两件事,使用 python,80% 的代码将是 Pythonic。列表理解是不经常使用的“大事”(可读性)。
Is my choice, just more readable and saying exactly what you intend to do and portable across versions.
Edit: being 'pythonic' is a third thought to me over readability and performance... with these two things in mind, with python 80% of your code will be pythonic. list comprehension being the 'big thing' that isn't used as often (readability).
Python 3:
Python 2:
长答案
print >>> sys.stderr
在 Python3 中消失了。http://docs.python.org/3.0/whatsnew/3.0.html说:
对于我们许多人来说,将目标放在命令末尾感觉有些不自然。另一种选择
看起来更面向对象,并且优雅地从通用到特定。但请注意,
write
并不是print
的 1:1 替代品。Python 3:
Python 2:
Long answer
print >> sys.stderr
is gone in Python3.http://docs.python.org/3.0/whatsnew/3.0.html says:
For many of us, it feels somewhat unnatural to relegate the destination to the end of the command. The alternative
looks more object oriented, and elegantly goes from the generic to the specific. But note that
write
is not a 1:1 replacement forprint
.还没有人提到
日志记录
,但日志记录是专门创建的传达错误消息。基本配置将设置一个写入 stderr 的流处理程序。该脚本:
在命令行上运行时具有以下结果:
并且 bar.txt 将包含打印在标准输出上的“hello world”。
Nobody's mentioned
logging
yet, but logging was created specifically to communicate error messages. Basic configuration will set up a stream handler writing to stderr.This script:
has the following result when run on the command line:
and bar.txt will contain the 'hello world' printed on stdout.
对于 Python 2 我的选择是:
打印>> sys.stderr,'垃圾邮件'
因为您可以简单地打印列表/字典等,而无需将其转换为字符串。
打印>> sys.stderr, {'垃圾邮件': '垃圾邮件'}
而不是:
sys.stderr.write(str({'spam': 'spam'}))
For Python 2 my choice is:
print >> sys.stderr, 'spam'
Because you can simply print lists/dicts etc. without convert it to string.
print >> sys.stderr, {'spam': 'spam'}
instead of:
sys.stderr.write(str({'spam': 'spam'}))
我想说你的第一种方法:
是“一个......明显的方法”其他不满足规则#1(“美丽比丑陋更好。”)
-- 2020 年编辑 --
以上是我在 2011 年对 Python 2.7 的回答。既然 Python 3 已成为标准,我认为“正确”的答案是:
I would say that your first approach:
is the "One . . . obvious way to do it" The others don't satisfy rule #1 ("Beautiful is better than ugly.")
-- Edit for 2020 --
Above was my answer for Python 2.7 in 2011. Now that Python 3 is the standard, I think the "right" answer is:
我使用 Python 3 执行了以下操作:
因此,现在我可以添加关键字参数,例如,以避免回车:
I did the following using Python 3:
So now I'm able to add keyword arguments, for example, to avoid carriage return:
可以使用 print():
在Python 3中,几乎 框:
或:
这很简单,不需要包含除
sys.stderr
之外的任何内容。In Python 3, one can just use print():
almost out of the box:
or:
This is straightforward and does not need to include anything besides
sys.stderr
.这将模仿标准打印功能,但在 stderr 上输出
This will mimic the standard print function but output on stderr
编辑事后看来,我认为更改 sys.stderr 和看不到更新的行为可能会造成混淆,使得这个答案不如仅使用其他人指出的简单函数那么好。
使用partial只会节省1行代码。潜在的混乱不值得节省 1 行代码。
原始
为了使它更容易,这里有一个使用“partial”的版本,这对包装函数有很大帮助。
然后你可以像这样使用它
你可以通过执行以下操作来检查它是否打印到stderr而不是stdout(覆盖来自http://coreygoldberg.blogspot.com.au/2009/05/python-redirect-or-turn-off-stdout-and。 html):
这样做的缺点是在创建时将 sys.stderr 的值部分分配给包装函数。这意味着,如果您稍后重定向 stderr,则不会影响此功能。
如果您打算重定向 stderr,请使用本页上 aaguirre 提到的 **kwargs 方法。
EDIT In hind-sight, I think the potential confusion with changing sys.stderr and not seeing the behaviour updated makes this answer not as good as just using a simple function as others have pointed out.
Using partial only saves you 1 line of code. The potential confusion is not worth saving 1 line of code.
original
To make it even easier, here's a version that uses 'partial', which is a big help in wrapping functions.
You then use it like so
You can check that it's printing to stderr and not stdout by doing the following (over-riding code from http://coreygoldberg.blogspot.com.au/2009/05/python-redirect-or-turn-off-stdout-and.html):
The downside to this is partial assigns the value of sys.stderr to the wrapped function at the time of creation. Which means, if you redirect stderr later it won't affect this function.
If you plan to redirect stderr, then use the **kwargs method mentioned by aaguirre on this page.
这同样适用于 stdout:
正如其他答案中所述,print 提供了一个漂亮的界面,通常更方便(例如用于打印调试信息),而 write 更快且更方便。当您必须以某种方式精确格式化输出时,也可以更方便。我也会考虑可维护性:
您稍后可能决定在 stdout/stderr 和常规文件之间切换。
print() 语法在 Python 3 中已更改,因此如果您需要支持这两个版本,write() 可能会更好。
The same applies to stdout:
As stated in the other answers, print offers a pretty interface that is often more convenient (e.g. for printing debug information), while write is faster and can also be more convenient when you have to format the output exactly in certain way. I would consider maintainability as well:
You may later decide to switch between stdout/stderr and a regular file.
print() syntax has changed in Python 3, so if you need to support both versions, write() might be better.
我正在 python 3.4.3 中工作。我正在删掉一些文字来显示我是如何到达这里的:
它有效吗?尝试将 stderr 重定向到一个文件,看看会发生什么:
嗯,除了 python 给你的小介绍已经被吞入 stderr 之外(它还会去哪里?),它是有效的。
I am working in python 3.4.3. I am cutting out a little typing that shows how I got here:
Did it work? Try redirecting stderr to a file and see what happens:
Well, aside from the fact that the little introduction that python gives you has been slurped into stderr (where else would it go?), it works.
如果您想因致命错误而退出程序,请
在标头中使用:和
import sys
。If you want to exit a program because of a fatal error, use:
and
import sys
in the header.如果你做一个简单的测试:
你会发现 sys.stderr.write() 始终快 1.81 倍!
If you do a simple test:
You will find that sys.stderr.write() is consistently 1.81 times faster!
print 和 stderr 的 write 函数的区别:
stderr :stderr(标准错误)是内置于每个 UNIX/Linux 系统中的管道,当程序崩溃并打印出调试信息(如 Python 中的回溯)时,它会转到 stderr 管道。
print:print是一个包装器,它格式化输入(输入是参数和末尾换行符之间的空格),然后调用给定对象的write函数,给定对象默认为sys.stdout,但我们可以传递一个文件,即我们也可以打印文件中的输入。
Python2:
如果我们使用 python2 那么
http://python3porting.com/noconv.html
注意:我们还可以使用日志记录https://docs.python.org/2/library/logging.html#logger-objects
The differnce between print and stderr's write function:
stderr : stderr (standard error) is pipe that is built into every UNIX/Linux system, when your program crashes and prints out debugging information (like a traceback in Python), it goes to the stderr pipe.
print: print is a wrapper that formats the inputs (the input is the space between argument and the newline at the end) and it then calls the write function of a given object, the given object by default is sys.stdout, but we can pass a file i.e we can print the input in a file also.
Python2:
If we are using python2 then
http://python3porting.com/noconv.html
https://docs.python.org/2/library/logging.html#logger-objects
另一种方式
Another way
我这样做只是为了好玩,但这是另一种方式......:-)
Im doing this just for fun but here is another way... :-)