有几种方法可以写入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 3执行了以下操作:

from sys import stderr

def print_err(*args, **kwargs):
    print(*args, file=stderr, **kwargs)

因此,现在我可以添加关键字参数,例如,以避免回车:

print_err("Error: end of the file reached. The word ", end='')
print_err(word, "was not found")

其他回答

import sys
sys.stderr.write()

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

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

在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之外的任何内容。

我想说你的第一个方法是:

print >> sys.stderr, 'spam' 

是“一个……显而易见的方法”,其他人不满足规则1(“漂亮总比丑陋好”)

--2020年编辑--

以上是我在2011年对Python 2.7的回答。既然Python 3是标准,我认为“正确”的答案是:

print("spam", file=sys.stderr) 

我在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(它还会去哪里?)之外,它还是有效的。

另一种方式

import sys
print("{}".format(sys.exec_info()[1], file=sys.stderr)