欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳細介紹Python進度條tqdm的使用

 更新時間:2019年07月31日 10:44:57   作者:修煉之路  
這篇文章主要介紹了詳細介紹Python進度條tqdm的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前言

有時候在使用Python處理比較耗時操作的時候,為了便于觀察處理進度,這時候就需要通過進度條將處理情況進行可視化展示,以便我們能夠及時了解情況。這對于第三方庫非常豐富的Python來說,想要實現(xiàn)這一功能并不是什么難事。

tqdm就能非常完美的支持和解決這些問題,可以實時輸出處理進度而且占用的CPU資源非常少,支持windowsLinux、mac等系統(tǒng),支持循環(huán)處理、多進程遞歸處理、還可以結合linux的命令來查看處理情況,等進度展示。

大家先看看tqdm的進度條效果

安裝

github地址:https://github.com/tqdm/tqdm

想要安裝tqdm也是非常簡單的,通過pip或conda就可以安裝,而且不需要安裝其他的依賴庫

pip安裝

pip install tqdm

conda安裝

conda install -c conda-forge tqdm

迭代對象處理

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

from tqdm import tqdm
import time

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


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

from tqdm import tqdm,trange
import time

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

觀察處理的數(shù)據(jù)

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

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)

手動設置處理的進度

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

from tqdm import tqdm
import time

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


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

from tqdm import tqdm
import time

#total參數(shù)設置進度條的總長度
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的參數(shù)控制進度條

$ 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)

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()

多層循環(huán)進度條

通過tqdm也可以很簡單的實現(xiàn)嵌套循環(huán)進度條的展示

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)


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

多進程進度條

在使用多進程處理任務的時候,通過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))

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)

遞歸使用進度條

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:/")

注意

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

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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • Python實現(xiàn)指定區(qū)域桌面變化監(jiān)控并報警

    Python實現(xiàn)指定區(qū)域桌面變化監(jiān)控并報警

    在這篇博客中,我們將使用Python編程語言和一些常用的庫來實現(xiàn)一個簡單的區(qū)域監(jiān)控和變化報警系統(tǒng),文中有詳細的代碼示例供大家參考,需要的朋友可以參考下
    2023-07-07
  • numpy ndarray 取出滿足特定條件的某些行實例

    numpy ndarray 取出滿足特定條件的某些行實例

    今天小編就為大家分享一篇numpy ndarray 取出滿足特定條件的某些行實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • Python基礎必備之語法結構詳解

    Python基礎必備之語法結構詳解

    Python語法定義了用于在 Python 編程中創(chuàng)建句子的所有規(guī)則集。如果想更深入地研究 Python 詞法結構,需要了解構成語句的句法元素,即構成 Python 程序的基本單元,涵蓋控制結構,在不同代碼組之間引導程序流的構造,快跟隨小編一起學習一下吧
    2022-04-04
  • Python標準庫datetime之datetime模塊用法分析詳解

    Python標準庫datetime之datetime模塊用法分析詳解

    這篇文章主要介紹了Python標準庫datetime之datetime模塊用法分析詳解,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-07-07
  • python3安裝crypto出錯及解決方法

    python3安裝crypto出錯及解決方法

    這篇文章主要介紹了python3安裝crypto出錯及解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-07-07
  • Python實現(xiàn)識別圖片為文字的示例代碼

    Python實現(xiàn)識別圖片為文字的示例代碼

    這篇文章主要為大家詳細介紹了Python如何不調用三方收費接口,照樣實現(xiàn)識別圖片為文字的功能。文中的示例代碼講解詳細,感興趣的可以了解一下
    2022-08-08
  • python在命令行下使用google翻譯(帶語音)

    python在命令行下使用google翻譯(帶語音)

    這篇文章主要介紹了使用google翻譯服務獲得翻譯和語音的示例,大家參考使用吧
    2014-01-01
  • Python實現(xiàn)將json文件生成C語言的結構體的腳本分享

    Python實現(xiàn)將json文件生成C語言的結構體的腳本分享

    這篇文章主要為大家詳細介紹了Python如何實現(xiàn)將json文件生成C語言的結構體,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2022-09-09
  • Python實現(xiàn)的密碼強度檢測器示例

    Python實現(xiàn)的密碼強度檢測器示例

    這篇文章主要介紹了Python實現(xiàn)的密碼強度檢測器,結合實例形式分析了Python密碼強度檢測的原理與實現(xiàn)方法,涉及Python字符串運算與轉換、判斷等相關操作技巧,需要的朋友可以參考下
    2017-08-08
  • wxPython:python首選的GUI庫實例分享

    wxPython:python首選的GUI庫實例分享

    wxPython是Python語言的一套優(yōu)秀的GUI圖形庫。允許Python程序員很方便的創(chuàng)建完整的、功能鍵全的GUI用戶界面。 wxPython是作為優(yōu)秀的跨平臺GUI庫wxWidgets的Python封裝和Python模塊的方式提供給用戶的
    2019-10-10

最新評論