Python在循环中显示进度条
本文代码转自 https://blog.csdn.net/u013832707/article/details/73608504,稍微做了一点魔改。
在训练模型时,往往有若干个迭代,想要实时显示训练进度,又不想每个迭代都输出而导致被刷屏,一种方法是显示进度条。
实际上就是输出控制,输入是当前迭代与总迭代次数,输出是进度条。每次输出完之后将之前的输出刷掉就可以了。
进度条代码
# coding:utf-8
import sys
class ProgressBar():
def __init__(self, max_steps):
self.max_steps = max_steps
self.current_step = 0
self.progress_width = 50
def update(self, step=None):
self.current_step = step
num_pass = int(self.current_step * self.progress_width / self.max_steps) + 1
num_rest = self.progress_width - num_pass
percent = (self.current_step+1) * 100.0 / self.max_steps
progress_bar = '[' + '■' * (num_pass-1) + '▶' + '-' * num_rest + ']'
progress_bar += '%.2f' % percent + '%'
if self.current_step < self.max_steps - 1:
progress_bar += '\r'
else:
progress_bar += '\n'
sys.stdout.write(progress_bar)
sys.stdout.flush()
if self.current_step >= self.max_steps:
self.current_step = 0
print
使用示例
max_batchs = 300
progress_bar = ProgressBar(max_batchs)
for iteration in range(max_batchs):
progress_bar.update(iteration)
# do something