python 进度条
一、print 实时刷新显示
# 利用打印功能print进行实时刷新显示
for i in range(1, 101):
print("\r", end="") # \r 表示将光标的位置回退到本行的开头位置
print("进度: {}%: ".format(i), "▓" * (i // 2), end="")
# print("进度: {}%: ".format(i), "▓" * (i // 2), end="", flush = True)
sys.stdout.flush() # flush 用于刷线缓存
time.sleep(0.05)
\r 表示将光标的位置回退到本行的开头位置
\b表示将光标的位置回退一位
python的标准输出也是被缓存起来的,这意味着该缓存会先收集数据,等缓存满了之后才会写入标准输出,然后这些数据会被写到终端或者其他输出流
print 输出会自动的刷新缓存,因为print默认时以‘\n’结尾
二、print 实时刷新显示 + 时间
# 通过print进行打印进度条,还加入了time时间显示,显示进度过程中所需要的时间
t = 60
print("**************带时间的进度条**************")
start = time.perf_counter() # 返回性能计数器的值(以分秒为单位)
for i in range(t + 1):
finsh = "▓" * i
need_do = "-" * (t - i)
progress = (i / t) * 100
dur = time.perf_counter() - start #这个函数计数值起点不确定,连续调用差值才有意义
print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(progress, finsh, need_do, dur), end="")
time.sleep(0.05)
time.perf_counter() 返回性能计数器的值(以分秒为单位); 这个函数计数值起点不确定,连续调用差值才有意义
三、tqdm 库
from tqdm import tqdm
for i in tqdm(range(1, 60)):
time.sleep(0.05)
其他库:alive_progress库、progressbar库、PySimpleGUI库
参考:https://blog.csdn.net/weixin_42686892/article/details/121958157