怎么在Python中利用tqdm实现一个进度条

发布时间:2021-03-24 15:54:05 作者:Leah
来源:亿速云 阅读:349

这期内容当中小编将会给大家带来有关怎么在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实现一个进度条了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 怎么在vue中利用nprogress实现一个页面顶部进度条
  2. 怎么在React中利用Native实现一个进度条弹框

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python tqdm

上一篇:如何使用PyQt5控件

下一篇:怎么在Win10系统中使用活动目录

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》