有几种方法可以写入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)
这些方法之间有什么区别?应首选哪种方法?
有几种方法可以写入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")
其他回答
问题的答案是:在python中打印stderr有不同的方法,但这取决于1.)我们正在使用哪个python版本2.)我们想要的确切输出。
print和stderr的write函数之间的区别:stderr:stderr(标准错误)是内置在每个UNIX/Linux系统中的管道,当程序崩溃并打印出调试信息(如Python中的回溯)时,它会进入stderr管道。
print:print是一个包装器,它格式化输入(输入是参数和末尾换行符之间的空格),然后调用给定对象的write函数,默认情况下,给定对象是sys.stdout,但我们可以传递一个文件,也就是说,我们也可以在文件中打印输入。
蟒蛇2:如果我们使用的是python2,那么
>>> import sys
>>> print "hi"
hi
>>> print("hi")
hi
>>> print >> sys.stderr.write("hi")
hi
Python2结尾的逗号在Python3中变成了一个参数,所以如果我们使用尾随逗号以避免打印后出现换行符,这将在Python3看起来像print(“要打印的文本”,end=“”),这是一种语法Python2下的错误。
http://python3porting.com/noconv.html
如果我们在python3中检查上述sceario:
>>> import sys
>>> print("hi")
hi
在Python2.6下,有一个将来的导入,可以将打印转换为作用因此,为了避免任何语法错误和其他差异,我们应该从将来的导入开始使用print()的任何文件print_函数。未来的导入仅适用于Python 2.6和稍后,对于Python 2.5和更早版本,您有两个选项。你可以或者将更复杂的打印转换为更简单的打印,或者您可以使用在Python2和蟒蛇3。
>>> from __future__ import print_function
>>>
>>> def printex(*args, **kwargs):
... print(*args, file=sys.stderr, **kwargs)
...
>>> printex("hii")
hii
>>>
案例:需要注意的是sys.stderr.write()或sys.stdout.write(stdout(标准输出)是一个管道UNIX/Linux系统)不是打印的替代品,但我们可以使用在某些情况下,它是一种选择。打印是包装在末尾输入空格和换行符,并使用write函数写这就是sys.stderr.write()更快的原因。注意:我们还可以使用日志记录跟踪和调试
#test.py
import logging
logging.info('This is the existing protocol.')
FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning("Protocol problem: %s", "connection reset", extra=d)
https://docs.python.org/2/library/logging.html#logger-对象
我发现这是唯一一个简短、灵活、便携和可读的:
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
可选函数eprint可以节省一些重复。它可以以与标准打印功能相同的方式使用:
>>> print("Test")
Test
>>> eprint("Test")
Test
>>> eprint("foo", "bar", "baz", sep="---")
foo---bar---baz
如果进行简单测试:
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倍!
还没有人提到日志记录,但日志记录是专门为传递错误消息而创建的。基本配置将设置写入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”。
在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之外的任何内容。