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

其他回答

EDIT在事后看来,我认为更改sys.stderr和没有看到行为更新可能会产生混淆,这使得这个答案不如其他人指出的那样简单。

使用partial只会节省1行代码。潜在的混淆不值得保存一行代码。

起初的

为了更简单,这里有一个使用“partial”的版本,这对包装函数有很大帮助。

from __future__ import print_function
import sys
from functools import partial

error = partial(print, file=sys.stderr)

然后你就这样使用它

error('An error occured!')

您可以通过执行以下操作(从http://coreygoldberg.blogspot.com.au/2009/05/python-redirect-or-turn-off-stdout-and.html):

# over-ride stderr to prove that this function works.
class NullDevice():
    def write(self, s):
        pass
sys.stderr = NullDevice()

# we must import print error AFTER we've removed the null device because
# it has been assigned and will not be re-evaluated.
# assume error function is in print_error.py
from print_error import error

# no message should be printed
error("You won't see this error!")

这样做的缺点是在创建时将sys.stderr的值部分分配给包装函数。这意味着,如果稍后重定向stderr,则不会影响此函数。如果您计划重定向stderr,请使用aaguirre在本页中提到的**kwargs方法。

这同样适用于标准输出:

print 'spam'
sys.stdout.write('spam\n')

如其他答案所述,打印提供了一个漂亮的界面,通常更方便(例如,用于打印调试信息),而写入速度更快,并且在必须以某种方式精确格式化输出时也更方便。我也会考虑可维护性:

您可以稍后决定在stdout/stderr和常规文件之间切换。print()语法在Python3中发生了变化,因此如果您需要同时支持这两个版本,write()可能会更好。

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

print >> sys.stderr, 'spam' 

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

--2020年编辑--

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

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

这将模拟标准打印函数,但输出到stderr

def print_err(*args):
    sys.stderr.write(' '.join(map(str,args)) + '\n')

如果由于严重错误而要退出程序,请使用:

sys.exit("Your program caused a fatal error. ... description ...")

并在标头中导入sys。