gpt4 book ai didi

Python 记录到标准输出和 StringIO

转载 作者:太空宇宙 更新时间:2023-11-04 05:18:00 39 4
gpt4 key购买 nike

尝试[ see it running here ]:

from sys import stdout, stderr
from cStringIO import StringIO
from logging import getLogger, basicConfig, StreamHandler

basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M')

log = getLogger(__name__)
sio = StringIO()
console = StreamHandler(sio)

log.addHandler(console)
log.addHandler(StreamHandler(stdout))

log.info('Jackdaws love my big sphinx of quartz.')
print 'console.stream.read() = {!r}'.format(console.stream.read())

输出[标准输出]:

console.stream.read() = ''

预期输出 [标准输出]:

[date] [filename] INFO Jackdaws love my big sphinx of quartz.
console.stream.read() = 'Jackdaws love my big sphinx of quartz.'

最佳答案

这里发生了两件事。

首先,root logger 被实例化为 WARNING 级别,这意味着级别低于 WARNING 的消息将不会被处理。您可以使用 Logger.setLevel(level) 设置级别,此处定义了级别 - https://docs.python.org/2/library/logging.html#levels .

正如评论中所建议的,日志级别也可以设置为:

basicConfig(level='INFO', ...)

其次,当您写入 StringIO 对象时,流中的位置设置在当前流的末尾。您需要倒回 StringIO 对象,然后才能从中读取。

console.stream.seek(0)
console.stream.read()

更简单,只需调用:

console.stream.getvalue()

完整代码:

from sys import stdout, stderr
from cStringIO import StringIO
from logging import getLogger, basicConfig, StreamHandler

basicConfig(format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M')

log = getLogger(__name__)
log.setLevel("INFO")
sio = StringIO()
console = StreamHandler(sio)

log.addHandler(console)
log.addHandler(StreamHandler(stdout))

log.info('Jackdaws love my big sphinx of quartz.')
console.stream.seek(0)
print 'console.stream.read() = {!r}'.format(console.stream.read())

关于Python 记录到标准输出和 StringIO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41215236/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com