2018-10-08
Python – 如何在Python中打印到stderr?
我有几种方法可以写入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 †的禅相矛盾,那么首选方法是什么?这种或那种方式有任何优点或缺点吗?
应该有一个 – 最好只有一个 – 显而易见的方法。
我发现这是唯一一个短+灵活+便携+可读:
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
sys.stderr.write()
是我的选择,只是更具可读性,并准确地说明你打算做什么,并且可以跨版本移植。
编辑:成为’pythonic’是第三个想到我的可读性和性能……考虑到这两个方面,python 80%的代码将是pythonic。列表理解是不常用的“大事”(可读性)。
对于Python 2,我的选择是: print >> sys.stderr, 'spam'
因为你可以简单地打印列表/ dicts等而不将其转换为字符串。 print >> sys.stderr, {'spam': 'spam'}
代替: sys.stderr.write(str({'spam': 'spam'}))
rint >> sys.stderr
在Python3中消失了。 http://docs.python.org/3.0/whatsnew/3.0.html说:
Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)
不幸的是,这非常难看。或者,使用
sys.stderr.write("fatal error\n")
还没logging
有人提到过,但是专门为了传递错误消息而创建了日志记录。默认情况下,它设置为写入stderr。这个脚本:
# foo.py
import logging
logging.basicConfig(format='%(message)s')
logging.warn('I print to stderr by default')
logging.info('For this you must change the level and add a handler.')
print('hello world')
在命令行上运行时,结果如下:
$ python3 foo.py > bar.txt
I print to stderr by default
(和bar.txt包含’hello world’)