我有一个简单的问题:如何将内置 Python 记录器的print
功能更改为tqdm.write
使记录消息不会干扰 tqdm 的进度条?谢谢!
问问题
23275 次
5 回答
42
您需要一个自定义日志记录处理程序:
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 Exception:
self.handleError(record)
然后将其添加到日志链中:
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-harmful/)
于 2016-08-03T09:28:06.213 回答
16
tqdm
现在有一个用于重定向记录器的内置上下文管理器:
import logging
from tqdm import trange
from tqdm.contrib.logging import logging_redirect_tqdm
LOG = logging.getLogger(__name__)
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
with logging_redirect_tqdm():
for i in trange(9):
if i == 4:
LOG.info("console logging redirected to `tqdm.write()`")
# logging restored
于 2021-09-11T18:00:43.817 回答
2
最简单的方法是更改StreamHandler
对象流,例如:
import logging
from tqdm import tqdm, trange
import time
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setStream(tqdm) # <-- important
handler = log.addHandler(handler)
for i in trange(100):
if i == 50:
log.info("Half-way there!")
time.sleep(0.1)
于 2021-04-01T14:09:57.123 回答
1
根据上面 RolKau 的回答,简化:
import logging
from tqdm import tqdm
class TqdmLoggingHandler(logging.StreamHandler):
"""Avoid tqdm progress bar interruption by logger's output to console"""
# see logging.StreamHandler.eval method:
# https://github.com/python/cpython/blob/d2e2534751fd675c4d5d3adc208bf4fc984da7bf/Lib/logging/__init__.py#L1082-L1091
# and tqdm.write method:
# https://github.com/tqdm/tqdm/blob/f86104a1f30c38e6f80bfd8fb16d5fcde1e7749f/tqdm/std.py#L614-L620
def emit(self, record):
try:
msg = self.format(record)
tqdm.write(msg, end=self.terminator)
except RecursionError:
raise
except Exception:
self.handleError(record)
测试:
import time
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
log.addHandler(TqdmLoggingHandler())
# ^-- Assumes this will be the unique handler emitting messages to sys.stdout.
# If other handlers output to sys.stdout (without tqdm.write),
# progress bar will be interrupted by those outputs
for i in tqdm(range(20)):
log.info(f"Looping {i}")
time.sleep(0.1)
警告:如果您在 Jupyter 笔记本中工作,进度条将被打断,AFAIK 无法避免。
于 2021-04-25T19:37:45.220 回答
1
一种不那么优雅的简单解决方案是将 tqdm 对象转换为字符串。之后,您可以记录消息(或根据需要处理)。“format_dict”属性也可能有用:
from tqdm import tqdm
import time
#loop with progressbar:
it=tqdm(total=10)
for i in range(10):
time.sleep(0.1)
it.update(1)
it.close()
print("\n","--"*10)
# Convert tdqm object last output to sting
str_bar_msg = str(it)
print(str_bar_msg)
# See attributes:
print(it.format_dict)
输出:
100%|██████████| 10/10 [00:01<00:00, 8.99it/s]
--------------------
100%|██████████| 10/10 [00:01<00:00, 8.98it/s]
{'n': 10, 'total': 10, 'elapsed': 1.1145293712615967, 'ncols': None, 'nrows': None, 'prefix': '', 'ascii': False, 'unit': 'it', 'unit_scale': False, 'rate': None, 'bar_format': None, 'postfix': None, 'unit_divisor': 1000, 'initial': 0, 'colour': None}
此致
于 2020-11-25T20:15:24.403 回答