最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳細(xì)介紹Python進(jìn)度條tqdm的使用

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

前言

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

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

大家先看看tqdm的進(jìn)度條效果

安裝

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

想要安裝tqdm也是非常簡(jiǎn)單的,通過(guò)pip或conda就可以安裝,而且不需要安裝其他的依賴庫(kù)

pip安裝

pip install tqdm

conda安裝

conda install -c conda-forge tqdm

迭代對(duì)象處理

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

from tqdm import tqdm
import time

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


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

from tqdm import tqdm,trange
import time

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

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

通過(guò)tqdm提供的set_description方法可以實(shí)時(shí)查看每次處理的數(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)

手動(dòng)設(shè)置處理的進(jìn)度

通過(guò)update方法可以控制每次進(jìn)度條更新的進(jìn)度

from tqdm import tqdm
import time

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


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

from tqdm import tqdm
import time

#total參數(shù)設(shè)置進(jìn)度條的總長(zhǎng)度
pbar = tqdm(total=100)
for i in range(100):
  time.sleep(0.05)
  #每次更新進(jìn)度條的長(zhǎng)度
  pbar.update(1)
#關(guān)閉占用的資源
pbar.close()

linux命令展示進(jìn)度條

不使用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ù)控制進(jìn)度條

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

自定義進(jìn)度條顯示信息

通過(guò)set_descriptionset_postfix方法設(shè)置進(jìn)度條顯示信息

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

with trange(100) as t:
  for i in t:
    #設(shè)置進(jìn)度條左邊顯示的信息
    t.set_description("GEN %i"%i)
    #設(shè)置進(jìn)度條右邊顯示的信息
    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)進(jìn)度條

通過(guò)tqdm也可以很簡(jiǎn)單的實(shí)現(xiàn)嵌套循環(huán)進(jì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í)行以上代碼的時(shí)候,會(huì)出現(xiàn)進(jìn)度條位置錯(cuò)亂,目前官方并沒(méi)有給出好的解決方案,這是由于pycharm不支持某些字符導(dǎo)致的,不過(guò)可以將上面的代碼保存為腳本然后在命令行中執(zhí)行,效果如下

多進(jìn)程進(jìn)度條

在使用多進(jìn)程處理任務(wù)的時(shí)候,通過(guò)tqdm可以實(shí)時(shí)查看每一個(gè)進(jìn)程任務(wù)的處理情況

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)

遞歸使用進(jìn)度條

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顯示進(jìn)度條的時(shí)候,如果代碼中存在print可能會(huì)導(dǎo)致輸出多行進(jìn)度條,此時(shí)可以將print語(yǔ)句改為tqdm.write,代碼如下

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Windows安裝多個(gè)不同版本Python并切換使用的步驟

    Windows安裝多個(gè)不同版本Python并切換使用的步驟

    這篇文章主要介紹了如何在已安裝Python?3.11的Windows電腦上安裝并切換到Python?3.9,首先下載并安裝Python?3.9,然后通過(guò)修改系統(tǒng)環(huán)境變量的Path來(lái)優(yōu)先使用Python?3.9,需要的朋友可以參考下
    2024-11-11
  • 快速進(jìn)修Python指南之面向?qū)ο蠡A(chǔ)

    快速進(jìn)修Python指南之面向?qū)ο蠡A(chǔ)

    這篇文章主要為大家介紹了Java開(kāi)發(fā)者快速進(jìn)修Python指南之面向?qū)ο蠡A(chǔ),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • 深入淺析Python傳值與傳址

    深入淺析Python傳值與傳址

    這篇文章主要介紹了Python傳值與傳址的相關(guān)知識(shí),包括傳值與傳址的區(qū)別介紹,需要的朋友可以參考下
    2018-07-07
  • 解決Pytorch內(nèi)存溢出,Ubuntu進(jìn)程killed的問(wèn)題

    解決Pytorch內(nèi)存溢出,Ubuntu進(jìn)程killed的問(wèn)題

    這篇文章主要介紹了解決Pytorch內(nèi)存溢出,Ubuntu進(jìn)程killed的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。
    2021-05-05
  • PyTorch手寫數(shù)字?jǐn)?shù)據(jù)集進(jìn)行多分類

    PyTorch手寫數(shù)字?jǐn)?shù)據(jù)集進(jìn)行多分類

    這篇文章主要介紹了PyTorch手寫數(shù)字?jǐn)?shù)據(jù)集進(jìn)行多分類,損失函數(shù)采用交叉熵,激活函數(shù)采用ReLU,優(yōu)化器采用帶有動(dòng)量的mini-batchSGD算法,需要的朋友可以參考一下
    2022-03-03
  • 強(qiáng)悍的Python讀取大文件的解決方案

    強(qiáng)悍的Python讀取大文件的解決方案

    今天小編就為大家分享一篇關(guān)于強(qiáng)悍的Python讀取大文件的解決方案,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-02-02
  • python/golang 刪除鏈表中的元素

    python/golang 刪除鏈表中的元素

    這篇文章主要介紹了python/golang 如何刪除鏈表中的元素,幫助大家更好的理解和使用python/golang,感興趣的朋友可以了解下
    2020-09-09
  • 詳解Django中的過(guò)濾器

    詳解Django中的過(guò)濾器

    這篇文章主要介紹了Django中的過(guò)濾器,Django是重多高人氣Python框架中最為著名的一個(gè),需要的朋友可以參考下
    2015-07-07
  • python實(shí)現(xiàn)實(shí)時(shí)視頻流播放代碼實(shí)例

    python實(shí)現(xiàn)實(shí)時(shí)視頻流播放代碼實(shí)例

    這篇文章主要介紹了python實(shí)現(xiàn)實(shí)時(shí)視頻流播放代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-01-01
  • Python迭代器協(xié)議及for循環(huán)工作機(jī)制詳解

    Python迭代器協(xié)議及for循環(huán)工作機(jī)制詳解

    這篇文章主要介紹了Python迭代器協(xié)議及for循環(huán)工作機(jī)制詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07

最新評(píng)論

田阳县| 万盛区| 阿勒泰市| 威信县| 上饶县| 贞丰县| 太仆寺旗| 五台县| 白水县| 大邑县| 博客| 武宣县| 汉中市| 赞皇县| 玉田县| 扎赉特旗| 浠水县| 车险| 重庆市| 民丰县| 浦东新区| 石狮市| 阿荣旗| 霍林郭勒市| 龙里县| 东方市| 辽阳市| 莫力| 波密县| 济阳县| 深州市| 民乐县| 沈丘县| 临洮县| 招远市| 安吉县| 藁城市| 临邑县| 栾城县| 京山县| 申扎县|