溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Python中利用tqdm實現一個進度條

發布時間:2021-03-24 15:54:05 來源:億速云 閱讀:387 作者:Leah 欄目:開發技術

這期內容當中小編將會給大家帶來有關怎么在Python中利用tqdm實現一個進度條,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

安裝

pip安裝

pip install tqdm

conda安裝

conda install -c conda-forge tqdm

迭代對象處理

對于可以迭代的對象都可以使用下面這種方式,來實現可視化進度,非常方便

from tqdm import tqdm
import time

for i in tqdm(range(100)):
  time.sleep(0.1)
  pass

怎么在Python中利用tqdm實現一個進度條

在使用tqdm的時候,可以將tqdm(range(100))替換為trange(100)代碼如下

from tqdm import tqdm,trange
import time

for i in trange(100):
  time.sleep(0.1)
  pass

觀察處理的數據

通過tqdm提供的set_description方法可以實時查看每次處理的數據

from tqdm import tqdm
import time

pbar = tqdm(["a","b","c","d"])
for c in pbar:
  time.sleep(1)
  pbar.set_description("Processing %s"%c)

怎么在Python中利用tqdm實現一個進度條

手動設置處理的進度

通過update方法可以控制每次進度條更新的進度

from tqdm import tqdm
import time

#total參數設置進度條的總長度
with tqdm(total=100) as pbar:
  for i in range(100):
    time.sleep(0.05)
    #每次更新進度條的長度
    pbar.update(1)

怎么在Python中利用tqdm實現一個進度條

除了使用with之外,還可以使用另外一種方法實現上面的效果

from tqdm import tqdm
import time

#total參數設置進度條的總長度
pbar = tqdm(total=100)
for i in range(100):
  time.sleep(0.05)
  #每次更新進度條的長度
  pbar.update(1)
#關閉占用的資源
pbar.close()

linux命令展示進度條

不使用tqdm

$ time find . -name '*.py' -type f -exec cat \{} \; | wc -l
857365

real  0m3.458s
user  0m0.274s
sys   0m3.325s

使用tqdm

$ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l
857366it [00:03, 246471.31it/s]
857365

real  0m3.585s
user  0m0.862s
sys   0m3.358s

指定tqdm的參數控制進度條

$ find . -name '*.py' -type f -exec cat \{} \; |
  tqdm --unit loc --unit_scale --total 857366 >> /dev/null
100%|███████████████████████████████████| 857K/857K [00:04<00:00, 246Kloc/s]
$ 7z a -bd -r backup.7z docs/ | grep Compressing |
  tqdm --total $(find docs/ -type f | wc -l) --unit files >> backup.log
100%|███████████████████████████████▉| 8014/8014 [01:37<00:00, 82.29files/s]

自定義進度條顯示信息

通過set_descriptionset_postfix方法設置進度條顯示信息

from tqdm import trange
from random import random,randint
import time

with trange(100) as t:
  for i in t:
    #設置進度條左邊顯示的信息
    t.set_description("GEN %i"%i)
    #設置進度條右邊顯示的信息
    t.set_postfix(loss=random(),gen=randint(1,999),str="h",lst=[1,2])
    time.sleep(0.1)

怎么在Python中利用tqdm實現一個進度條

from tqdm import tqdm
import time

with tqdm(total=10,bar_format="{postfix[0]}{postfix[1][value]:>9.3g}",
     postfix=["Batch",dict(value=0)]) as t:
  for i in range(10):
    time.sleep(0.05)
    t.postfix[1]["value"] = i / 2
    t.update()

怎么在Python中利用tqdm實現一個進度條

多層循環進度條

通過tqdm也可以很簡單的實現嵌套循環進度條的展示

from tqdm import tqdm
import time

for i in tqdm(range(20), ascii=True,desc="1st loop"):
  for j in tqdm(range(10), ascii=True,desc="2nd loop"):
    time.sleep(0.01)

怎么在Python中利用tqdm實現一個進度條

pycharm中執行以上代碼的時候,會出現進度條位置錯亂,目前官方并沒有給出好的解決方案,這是由于pycharm不支持某些字符導致的,不過可以將上面的代碼保存為腳本然后在命令行中執行,效果如下

怎么在Python中利用tqdm實現一個進度條

多進程進度條

在使用多進程處理任務的時候,通過tqdm可以實時查看每一個進程任務的處理情況

from time import sleep
from tqdm import trange, tqdm
from multiprocessing import Pool, freeze_support, RLock

L = list(range(9))

def progresser(n):
  interval = 0.001 / (n + 2)
  total = 5000
  text = "#{}, est. {:<04.2}s".format(n, interval * total)
  for i in trange(total, desc=text, position=n,ascii=True):
    sleep(interval)

if __name__ == '__main__':
  freeze_support() # for Windows support
  p = Pool(len(L),
       # again, for Windows support
       initializer=tqdm.set_lock, initargs=(RLock(),))
  p.map(progresser, L)
  print("\n" * (len(L) - 2))

怎么在Python中利用tqdm實現一個進度條

pandas中使用tqdm

import pandas as pd
import numpy as np
from tqdm import tqdm

df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))


tqdm.pandas(desc="my bar!")
df.progress_apply(lambda x: x**2)

怎么在Python中利用tqdm實現一個進度條

遞歸使用進度條

from tqdm import tqdm
import os.path

def find_files_recursively(path, show_progress=True):
  files = []
  # total=1 assumes `path` is a file
  t = tqdm(total=1, unit="file", disable=not show_progress)
  if not os.path.exists(path):
    raise IOError("Cannot find:" + path)

  def append_found_file(f):
    files.append(f)
    t.update()

  def list_found_dir(path):
    """returns os.listdir(path) assuming os.path.isdir(path)"""
    try:
      listing = os.listdir(path)
    except:
      return []
    # subtract 1 since a "file" we found was actually this directory
    t.total += len(listing) - 1
    # fancy way to give info without forcing a refresh
    t.set_postfix(dir=path[-10:], refresh=False)
    t.update(0) # may trigger a refresh
    return listing

  def recursively_search(path):
    if os.path.isdir(path):
      for f in list_found_dir(path):
        recursively_search(os.path.join(path, f))
    else:
      append_found_file(path)

  recursively_search(path)
  t.set_postfix(dir=path)
  t.close()
  return files

find_files_recursively("E:/")

怎么在Python中利用tqdm實現一個進度條

注意

在使用tqdm顯示進度條的時候,如果代碼中存在print可能會導致輸出多行進度條,此時可以將print語句改為tqdm.write,代碼如下

for i in tqdm(range(10),ascii=True):
  tqdm.write("come on")
  time.sleep(0.1)

上述就是小編為大家分享的怎么在Python中利用tqdm實現一個進度條了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女