通过将先前打印的进度条保存在函数属性中(请参阅https://www.python.org/dev/peps/pep-0232/),对进度功能进行相当简单的更改将确保它仅在要打印的进度条发生更改时打印和刷新:
import sys, time
def progress(count, total, status=''):
# make sure the saved bar is initialized
if not hasattr(progress,'lastbar'):
progress.lastbar = ""
bar_len = 60
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '=' * filled_len + '-' * (bar_len - filled_len)
# only print the bar if it is different from the previous bar
if bar != progress.lastbar:
sys.stdout.write('\r[%s] %s%s ...%s\r' % (bar, percents, '%', status))
sys.stdout.flush()
progress.lastbar = bar
total = 1000
i = 0
while i < total:
progress(i, total, status='Doing very long job')
# My long python program here
i += 1
上面的代码仅在条形本身发生变化时打印和刷新 - 所以 60 次而不是 1000 次 - 忽略显示的百分比和状态消息的变化 - 如果这些对你很重要,你可能想要存储和比较完整的打印线,像这样(但这会做更多的打印和更多的冲洗):
import sys, time
def progress(count, total, status=''):
if not hasattr(progress,'lastbar'):
progress.lastbar = ""
bar_len = 60
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '=' * filled_len + '-' * (bar_len - filled_len)
fullbar = '\r[%s] %s%s ...%s\r' % (bar, percents, '%', status)
if fullbar != progress.lastbar:
sys.stdout.write(fullbar)
sys.stdout.flush()
progress.lastbar = fullbar
total = 1000
i = 0
while i < total:
progress(i, total, status='Doing very long job')
# My long python program here
i += 1
我确信也可以使用更复杂的方法将“20 分之一”的逻辑构建到进度函数中。
可能构建条形图也是进度功能的一个昂贵部分 - 当输出不会改变时,您可以通过将 filled_len 与之前的 filled_len 进行比较来避免这种情况,甚至不构建如果值未更改,则为 bar 的字符串,如下所示:
import sys, time
def progress(count, total, status=''):
if not hasattr(progress,'lastlen'):
progress.lastlen = 0
bar_len = 60
filled_len = int(round(bar_len * count / float(total)))
if filled_len != progress.lastlen:
percents = round(100.0 * count / float(total), 1)
bar = '=' * filled_len + '-' * (bar_len - filled_len)
fullbar = '\r[%s] %s%s ...%s\r' % (bar, percents, '%', status)
sys.stdout.write(fullbar)
sys.stdout.flush()
progress.lastlen = filled_len
total = 1000
i = 0
while i < total:
progress(i, total, status='Doing very long job')
# My long python program here
i += 1