更改日志记录“打印"功能来"tqdm.write";因此记录不会干扰进度条 [英] Change logging "print" function to "tqdm.write" so logging doesn't interfere with progress bars
问题描述
我有一个简单的问题:如何将内置的Python记录器的print
函数更改为tqdm.write
,以使记录消息不会干扰tqdm的进度条?谢谢!
I have a simple question: How do I change the built-in Python logger's print
function to tqdm.write
such that logging messages do not interfere with tqdm's progress bars? Thanks!
推荐答案
您需要自定义日志记录处理程序:
You need a custom logging handler:
import logging
import tqdm
class TqdmLoggingHandler(logging.Handler):
def __init__(self, level=logging.NOTSET):
super().__init__(level)
def emit(self, record):
try:
msg = self.format(record)
tqdm.tqdm.write(msg)
self.flush()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
,然后将其添加到日志链:
and then add this to the logging chain:
import time
log = logging.getLogger (__name__)
log.setLevel (logging.INFO)
log.addHandler (TqdmLoggingHandler ())
for i in tqdm.tqdm (range (100)):
if i == 50:
log.info ("Half-way there!")
time.sleep (0.1)
修复了对超级TqdmLoggingHandler的init方法的调用中的一个错误,该错误已由勤奋的读者@BlaineRogers在评论中指出. (如果有人想进一步了解Python的这个阴暗区域,我建议 https://fuhm.net/super-有害/)
Fixed a bug in the call to super TqdmLoggingHandler's init method, that was pointed out by diligent reader @BlaineRogers in the comments. (If anyone wants to read further about this murky area of Python, I recommend https://fuhm.net/super-harmful/)
这篇关于更改日志记录“打印"功能来"tqdm.write";因此记录不会干扰进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!