代码 :
import sys
import time
class ProgressBar:
def __init__(self, total, desc="", size=40, symbol='█', file=sys.stderr):
self.total = total # 总长度
self.desc = desc # 文字说明
self.symbol = symbol # 进度条标志
self.size = size # 进度条总长度
self.file = file # 输出方式
self.current = 0 # 当前长度
self.start = time.time()
self.update(0)
def update(self, step=1):
"""更新进度条"""
# 更新当前长度
self.current += step
# 确定进度条字符的个数
x = int(self.current / self.total * self.size)
# 计算百分比
percentage = int(self.current / self.total * 100)
# 计算用时
d = int(time.time() - self.start)
duration = f'{d // 60:02d}:{d % 60:02d}'
# 输出
# \r:回车,即将光标移到行首,但是不会移到下一行,如果继续输入的话会覆盖掉前面的内容
fmt = f'\r{self.desc} |{self.symbol * x}{" " * (self.size - x)}| [{self.current}/{self.total}] [{percentage}%] [{duration}]'
print(fmt, file=self.file, end='')
if __name__ == '__main__':
bar = ProgressBar(total=15, desc='测试中...')
for i in range(15):
bar.update(1)
time.sleep(1)
运行效果:
1.pycharm:(理想效果)
2.命令行执行:(理想效果)
3.sublime_text:
参考:
给Python代码加上酷炫进度条的几种姿势 - 知乎 (zhihu.com)