通过记录模块的Python进度栏 [英] Python Progress Bar THROUGH Logging Module

查看:89
本文介绍了通过记录模块的Python进度栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中看到了不同的进度条解决方案,但是简单的stdout解决方案不适用于我的项目.我有多个类,并使用日志记录"模块将信息输出到STDOUT.我有一项功能,希望在一行上显示一个进度条,每次刷新缓冲区.

I have seen different solutions for a progress bar within Python, but the simple stdout solutions are not working for my project. I have multiple classes and use the "logging" module to output information to STDOUT. I have a function of which I want to show a progress bar on one line, flushing the buffer each time.

简单进度示例:

for i in range(100):
    time.sleep(1)
    sys.stdout.write("\r%d%%" %i)
    sys.stdout.flush()

当我尝试通过STDOUT进行写入然后刷新缓冲区时,要么缓冲区未刷新,要么进度没有任何进展.我希望避免某种线程化或复杂的过程来实现这一点.有人有实现此目的的首选方法吗?

When I try to write via STDOUT and then flush the buffer, either the buffer is not flushed or the progress doesn't go anywhere. I am hoping to avoid some sort of threading or complicated process to make this possible. Does someone have a preferred way of making this happen?

推荐答案

我为此找不到好的解决方案,所以我写了启发进度栏以对其进行处理.基本上,它会更改终端的滚动区域,以便在进度条上方进行记录,而不必在每次要写入STDOUT时都重新绘制进度条.这样一来,您无需修改​​日志记录打印,等等.

I couldn't find a good solution for this, so I wrote enlighten progress bar to handle it. Basically it changes the scroll area of the terminal so logging is done above the progress bar(s) rather than having to redraw the progress bar(s) every time you want to write to STDOUT. This lets you write to the terminal as much as you want without having to modify logging, print, etc.

import logging
import time
import enlighten

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()

# Setup progress bar
manager = enlighten.get_manager()
pbar = manager.counter(total=100, desc='Ticks', unit='ticks')

for i in range(1, 101):
    logger.info("Processing step %s" % i)
    time.sleep(.2)
    pbar.update()

这篇关于通过记录模块的Python进度栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆