Python文本进度条

Update:使用python库tqdm轻松实现

一个小程序,用Python在控制台中打印进度条,主要使用time库对时间进行控制,利用了\r转义符使光标回到当前行首的特性,通过多次打印进度条实现动画效果

代码

import time
scale = 50  # 进度条长度
print(">>执行开始\n")
start = time.perf_counter()  # 开始时刻

for i in range(scale+1):
    a = '|' * i
    b = '.' * (scale - i)
    c = (i / scale) * 100
    dur = time.perf_counter() - start  # 当前用时
    print("\r{:^3.0f}% [{}>>{}] {:.2f}s".format(c, a, b, dur), end='')  # 打印进度条
    time.sleep(0.1)  # 休息时间,调整速度

print("\n\n>>执行结束")

效果

Python进度条效果

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus