Python 動態(tài)進度條實現(xiàn)
在編寫Python腳本時,特別是在處理長時間運行的任務或者循環(huán)迭代的過程中,向用戶展示任務的執(zhí)行進度是非常重要的。進度條不僅能夠提高用戶體驗,還能讓用戶對程序的運行情況有一個直觀的了解。這篇文章將會介紹如何在Python中實現(xiàn)動態(tài)進度條,并通過多個實例來展示其實現(xiàn)方式。
1. 使用 print 函數(shù)
最簡單的方式是直接使用print函數(shù)來更新進度條的狀態(tài)。
示例代碼 1:
import time
def progress_bar(n, total, bar_length=20):
percent = float(n) / total
arrow = '-' * int(round(percent * bar_length) - 1) + '>'
spaces = ' ' * (bar_length - len(arrow))
print(f'Progress: [{arrow}{spaces}] {int(round(percent * 100))}%', end='\r')
total = 50
for i in range(total):
time.sleep(0.1) # 模擬耗時操作
progress_bar(i + 1, total)
print() # 打印換行
輸出結果:
Progress: [--------------------->] 100%
2. 使用 tqdm 庫
tqdm 是一個非常流行的進度條庫,它能夠輕松地為循環(huán)添加進度條。
示例代碼 2:
from tqdm import tqdm
import time
total = 50
for i in tqdm(range(total), desc="Processing"):
time.sleep(0.1) # 模擬耗時操作
輸出結果:
Processing: 100%|██████████| 50/50 [00:05<00:00, 9.82it/s]
3. 自定義樣式
tqdm 支持自定義樣式,比如顏色和字符。
示例代碼 3:
from tqdm import tqdm
import time
total = 50
for i in tqdm(range(total), desc="Processing", bar_format="{desc}: {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]"):
time.sleep(0.1) # 模擬耗時操作
輸出結果:
Processing: 50/50 [00:05<00:00, 9.82it/s]
4. 多進度條
有時候我們需要同時跟蹤多個進度條。
示例代碼 4:
from tqdm import tqdm
import time
with tqdm(total=100, desc="First") as pbar1, tqdm(total=100, desc="Second") as pbar2:
for i in range(100):
time.sleep(0.05)
pbar1.update(1)
pbar2.update(1)
輸出結果:
First: 100%|██████████| 100/100 [00:05<00:00, 19.31it/s]
Second: 100%|██████████| 100/100 [00:05<00:00, 19.31it/s]
5. 嵌套進度條
當你的任務是分層結構時,嵌套進度條會很有用。
示例代碼 5:
from tqdm import tqdm
import time
outer = tqdm(total=100, desc="Outer Loop")
for i in outer:
inner = tqdm(total=100, desc="Inner Loop", leave=False)
for j in inner:
time.sleep(0.01)
inner.update(1)
outer.update(1)
inner.close()
outer.close()
輸出結果:
Outer Loop: 100%|██████████| 100/100 [00:10<00:00, 9.78it/s]
6. 更新頻率控制
有時你需要控制進度條的更新頻率。
示例代碼 6:
from tqdm import tqdm
import time
total = 50
for i in tqdm(range(total), desc="Processing", mininterval=0.5):
time.sleep(0.1) # 模擬耗時操作
輸出結果:
Processing: 100%|██████████| 50/50 [00:05<00:00, 9.82it/s]
7. 動態(tài)描述
在循環(huán)中更新描述文本。
示例代碼 7:
from tqdm import tqdm
import time
total = 50
with tqdm(total=total, desc="Starting") as pbar:
for i in range(total):
time.sleep(0.1) # 模擬耗時操作
pbar.set_description(f"Processing {i+1}")
pbar.update(1)
輸出結果:
Processing 50: 100%|██████████| 50/50 [00:05<00:00, 9.82it/s]
8. 自定義回調
可以定義一個回調函數(shù)來處理進度條的更新。
示例代碼 8:
from tqdm import tqdm
import time
def update_progress(progress):
print(f"Progress: {progress}% completed.", end="\r")
total = 50
for i in range(total):
time.sleep(0.1) # 模擬耗時操作
update_progress(int((i + 1) / total * 100))
print() # 打印換行
輸出結果:
Progress: 100% completed.
9. 使用 click 庫
click 是一個用于構建命令行界面的庫,也可以用來顯示進度條。
示例代碼 9:
import click
import time
total = 50
with click.progressbar(range(total), label='Processing') as bar:
for i in bar:
time.sleep(0.1) # 模擬耗時操作
輸出結果:
Processing 50/50 [100%]
10. 使用 rich 庫
rich 是一個強大的庫,可以創(chuàng)建美觀的終端輸出,包括進度條。
示例代碼 10:
from rich.progress import track
import time
total = 50
for i in track(range(total), descriptinotallow="Processing..."):
time.sleep(0.1) # 模擬耗時操作
輸出結果:
Processing... 100% 50/50 [00:05<00:00, 9.82it/s]
通過上述示例,你可以看到不同的方法來實現(xiàn)動態(tài)進度條。選擇合適的方法取決于你的具體需求和場景。希望這些示例能幫助你在實際項目中有效地使用進度條功能!