有几种方法可以写入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)

这些方法之间有什么区别?应首选哪种方法?


当前回答

对于Python 2,我的选择是:print>>sys.stderr,“垃圾邮件”因为您可以简单地打印列表/字典等,而无需将其转换为字符串。print>>sys.stderr,{'spam':'spam'}而不是:sys.stderr.write(str({'spam':'spam'}))

其他回答

还没有人提到日志记录,但日志记录是专门为传递错误消息而创建的。基本配置将设置写入stderr的流处理程序。

此脚本:

# foo.py
import logging

logging.basicConfig(format='%(message)s')
log = logging.getLogger(__name__)
log.warning('I print to stderr by default')
print('hello world')

在命令行上运行时具有以下结果:

$ python3 foo.py > bar.txt
I print to stderr by default

bar.txt将包含打印在stdout上的“helloworld”。

import sys
sys.stderr.write()

是我的选择,只是更具可读性,更准确地说出您想要做的事情,并且可以跨版本移植。

编辑:在可读性和性能方面,“蟒蛇”是我的第三个想法。。。考虑到这两件事,使用python,80%的代码将是pythonic的。列表理解是不经常使用的“大事”(可读性)。

我在python 3.4.3中工作。我正在减少一点打字,显示我是如何来到这里的:

[18:19 jsilverman@JSILVERMAN-LT7 pexpect]$ python3
>>> import sys
>>> print("testing", file=sys.stderr)
testing
>>>
[18:19 jsilverman@JSILVERMAN-LT7 pexpect]$ 

它起作用了吗?尝试将stderr重定向到一个文件,看看会发生什么:

[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$ python3 2> /tmp/test.txt
>>> import sys
>>> print("testing", file=sys.stderr)
>>> [18:22 jsilverman@JSILVERMAN-LT7 pexpect]$
[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$ cat /tmp/test.txt
Python 3.4.3 (default, May  5 2015, 17:58:45)
[GCC 4.9.2] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
testing

[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$

好吧,除了python给你的小介绍已经被插入stderr(它还会去哪里?)之外,它还是有效的。

在Python 3中,可以只使用print():

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

几乎开箱即用:

import sys
print("Hello, world!", file=sys.stderr)

or:

from sys import stderr
print("Hello, world!", file=stderr)

这很简单,不需要包含除sys.stderr之外的任何内容。

如果进行简单测试:

import time
import sys

def run1(runs):
    x = 0
    cur = time.time()
    while x < runs:
        x += 1
        print >> sys.stderr, 'X'
    elapsed = (time.time()-cur)
    return elapsed

def run2(runs):
    x = 0
    cur = time.time()
    while x < runs:
        x += 1
        sys.stderr.write('X\n')
        sys.stderr.flush()
    elapsed = (time.time()-cur)
    return elapsed

def compare(runs):
    sum1, sum2 = 0, 0
    x = 0
    while x < runs:
        x += 1
        sum1 += run1(runs)
        sum2 += run2(runs)
    return sum1, sum2

if __name__ == '__main__':
    s1, s2 = compare(1000)
    print "Using (print >> sys.stderr, 'X'): %s" %(s1)
    print "Using (sys.stderr.write('X'),sys.stderr.flush()):%s" %(s2)
    print "Ratio: %f" %(float(s1) / float(s2))

你会发现sys.stderr.write()总是快1.81倍!