基础永远值得花费90%的精力去学习加强。认识实践的重要性。
Ax Python进度条的实现方法
进度条提供了可视化的进度情况,人我们不再误以为程序是卡死状态。
普通进度条
import sys
import time
def progress_bar():
for i in range(1, 101):
print("\r", end="")
print("Download progress: {}%:".format(i), "▋" * (i // 2), end="")
sys.stdout.flush()
time.sleep(0.05)
if __name__ == '__main__':
progress_bar()
# 当 __name__ 值为 "__main__" 的即为脚本,反之,即为导入的模块或者库(方法)。
# __name__在本文件执行则返回__main__,在其它文件调用则返回执行文件的名字。
效果
Download progress: 100%: ▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋
带时间进度条
import time
scale = 50
print("Start".center(scale // 2, "-"))
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" + "Done".center(scale // 2, "-"))
效果
----------Start----------
100%[**************************************************->]5.50s
-----------Done----------
TQDM模块
from time import sleep
from tqdm import tqdm
# 这里同样的,tqdm就是这个进度条最常用的一个方法
# 里面存一个可迭代对象
for i in tqdm(range(1, 500)):
# 模拟你的任务
sleep(0.01)
sleep(0.5)
效果
100%|██████████| 499/499 [00:07<00:00, 63.41it/s]
progress 进度条
文档:https://pypi.org/project/progress/
from progress.bar import Bar
bar = Bar('Processing', max=20)
for i in range(20):
# Do some work
bar.next()
bar.finish()
效果
Processing |################################| 20/20
例2
import time
from progress.bar import IncrementalBar
mylist = [1, 2, 3, 4, 5, 6, 7, 8]
bar = IncrementalBar('Countdown', max=len(mylist))
for item in mylist:
bar.next()
time.sleep(1)
bar.finish()
效果
Countdown |████ | 1/8
Countdown |████████ | 2/8
Countdown |████████████ | 3/8
Countdown |████████████████ | 4/8
Countdown |████████████████████ | 5/8
Countdown |████████████████████████ | 6/8
Countdown |████████████████████████████ | 7/8
alive_progress
文档:https://github.com/rsalmei/alive-progress
from alive_progress import alive_bar
import time
# retrieve your set of items
items = range(100)
# declare your expected total
with alive_bar(len(items)) as bar:
# iterate as usual
for item in items:
# process each item
bar()
time.sleep(0.1)
效果
|███████████████████████████▎ | ▆▄▂ 68/100 [68%] in 7s (9.2/s, eta: 4s)
PySimpleGUI库
import PySimpleGUI as sg
import time
count = range(100)
for i, item in enumerate(count):
sg.one_line_progress_meter('实时进度条', i + 1, len(count), '-key-')
"""
代码
"""
# 假设这代码部分需要0.05s
time.sleep(0.05)
效果
progressbar
from progressbar import *
import time
progress = ProgressBar()
for i in progress(range(1000)):
time.sleep(0.01)
效果
100% |########################################################################
Rich
文档:https://pypi.org/project/rich/
from rich.progress import track
import time
for step in track(range(30)):
time.sleep(0.5)
效果