用tqdm和rich為固定路徑和目標的python算法代碼實現進度條


適用場景

在存在固定長度的算法中可以可視化算法執行的過程,比如對一個固定長度的數組的遍歷,就是一種適合使用進度條來進行可視化的場景。而一些條件循環,比如while循環,不一定適合使用進度條來對算法執行過程進行可視化,典型的一個場景就是自洽的優化算法。

tqdm進度條的使用方法與效果

調用的方法也非常的容易,只需要將我們常用的range函數替換成tqdm中自帶的trange即可。

# test_tqdm.py
from tqdm import trange
import time
for i in trange(10):
    time.sleep(1)

以下是運行中間過程的一個顯示場景

[dechin@dechin-manjaro progressbar]$ python3 test_tqdm.py 
 40%|████████████████                        | 4/10 [00:04<00:06,  1.00s/it]

通過多次引用trange,還可以實現多個進度條打印的功能,但是這里如果第一層的數量較多,會導致屏幕輸出過於復雜:

# test_tqdm.py
from tqdm import trange
import time
for i in trange(10):
    for j in trange(10):
        time.sleep(0.1)

以下是執行過程中的輸出:

[dechin@dechin-20n2s01200 progressbar]$ python3 test_tqdm.py 
100%|███████████████████████████████████████| 10/10 [00:01<00:00,  9.88it/s]
100%|███████████████████████████████████████| 10/10 [00:01<00:00,  9.88it/s]
100%|███████████████████████████████████████| 10/10 [00:01<00:00,  9.88it/s]
 30%|████████████                            | 3/10 [00:03<00:07,  1.01s/it]

rich進度條的使用方法與效果

使用的方法與tqdm有些類似的,也是直接調用rich中的trackrange函數進行封裝:

# test_rich.py
from rich.progress import track
import time
for i in track(range(15)):
    time.sleep(1)

與簡單的tqdm不同的是,rich支持種類眾多的色彩,下面粘貼的執行過程顯示,其實是帶有彩色的:

[dechin@dechin-manjaro progressbar]$ python3 test_rich.py 
Working... ━━━━━━━━━━╸━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  27% 0:00:12

版權聲明

本文首發鏈接為:https://www.cnblogs.com/dechinphy/p/progress-bar.html
作者ID:DechinPhy
更多原著文章請參考:https://www.cnblogs.com/dechinphy/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM