百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python进度条tqdm你值得拥有(python2 进度条)

off999 2024-09-14 07:15 29 浏览 0 评论

前言

之所以了解到了这个,是因为使用了一个依赖tqdm的包,然后好奇就查了一下。对于python中的进度条也是经常使用的,例如包的安装,一些模型的训练也会通过进度条的方式体现在模型训练的进度。总之,使用进度条能够更加锦上添花,提升使用体验吧。至于更多tqdm内容可以参考tqdm官网[1]下面就来看看吧。

tqdm

1 简单了解

先来看看效果,使用循环显示一个智能的进度条-只需用tqdm(iterable)包装任何可迭代就可完成,如下:

tqdm运行

相关代码如下:

import tqdm
import time


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

官方也给了一张图,来看看:

run2

看起来还不错吧,现在我们详细地了解一下。

2 使用

安装就不用说了,使用pip install tqdm即可。tqdm主要有以下三种用法。

2.1 基于迭代器的(iterable-based)

使用案例如下,使用tqdm()传入任何可迭代的参数:

from tqdm import tqdm
from time import sleep


text = ""
for char in tqdm(["a", "b", "c", "d"]):
    sleep(0.25)
    text = text + char

tqdm(range(i))的一个特殊优化案例:

from time import sleep
from tqdm import trange

for i in trange(100):
    sleep(0.01)

这样就可以不同传入range(100)这样的迭代器了,trange()自己去构建。 除此之外,可以用tqdm()在循环外手动控制一个可迭代类型,如下:

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

这里还使用了.set_description(),结果如下:

Processing d: 100%|██████████| 4/4 [00:01<00:00,  3.99it/s]

相关参数容后再介绍。

2.2 手工操作(Manual)

使用with语句手动控制tqdm的更新,可以根据具体任务来更新进度条的进度。

with tqdm(total=100) as pbar:
    for i in range(10):
        sleep(0.1)
        pbar.update(10)

当然with这个语句想必大家都知道(想想使用with打开文件就知道了),也可以不使用with进行,则有如下操作:

pbar = tqdm(total=100)
for i in range(10):
    sleep(0.1)
    pbar.update(10)
pbar.close()

那么这个时候,就不要忘了在结束后关闭,或者del tqdm对象了。

2.3 模块(Module)

也许tqdm的最妙用法是在脚本中或在命令行中。只需在管道之间插入tqdm(或python -m tqdm),即可将所有stdin传递到stdout,同时将进度打印到stderr。具体如何操作,我们来看看,下面也是官方给出的例子。 以下示例演示了对当前目录中所有Python文件中的行数进行计数,其中包括计时信息。(为了能够在windows系统中使用linux命令,这是使用git打开),也是当前项目路径。

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

linux命令补充: time[2]find[3](-exec 使用其后参数操作查找到的文件);wc[4].

使用tqdm命令来试一试:

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

则有:

tqdm

注意,也可以指定tqdm的常规参数。如下:

就暂时说到这吧,感觉内容有点超纲了,如果对tqdm有兴趣的话可以访问官方文档深入了解。

3 参数

官方的类初始化代码如下:

class tqdm():
  """
  Decorate an iterable object, returning an iterator which acts exactly
  like the original iterable, but prints a dynamically updating
  progressbar every time a value is requested.
  """

  def __init__(self, iterable=None, desc=None, total=None, leave=True,
               file=None, ncols=None, mininterval=0.1,
               maxinterval=10.0, miniters=None, ascii=None, disable=False,
               unit='it', unit_scale=False, dynamic_ncols=False,
               smoothing=0.3, bar_format=None, initial=0, position=None,
               postfix=None, unit_divisor=1000):

官方对各个参数介绍如下:

Parameters
        ----------
        iterable  : iterable, optional
            Iterable to decorate with a progressbar.
            Leave blank to manually manage the updates.
        desc  : str, optional
            Prefix for the progressbar.
        total  : int, optional
            The number of expected iterations. If unspecified,
            len(iterable) is used if possible. If float("inf") or as a last
            resort, only basic progress statistics are displayed
            (no ETA, no progressbar).
            If `gui` is True and this parameter needs subsequent updating,
            specify an initial arbitrary large positive integer,
            e.g. int(9e9).
        leave  : bool, optional
            If [default: True], keeps all traces of the progressbar
            upon termination of iteration.
        file  : `io.TextIOWrapper` or `io.StringIO`, optional
            Specifies where to output the progress messages
            (default: sys.stderr). Uses `file.write(str)` and `file.flush()`
            methods.  For encoding, see `write_bytes`.
        ncols  : int, optional
            The width of the entire output message. If specified,
            dynamically resizes the progressbar to stay within this bound.
            If unspecified, attempts to use environment width. The
            fallback is a meter width of 10 and no limit for the counter and
            statistics. If 0, will not print any meter (only stats).
        mininterval  : float, optional
            Minimum progress display update interval [default: 0.1] seconds.
        maxinterval  : float, optional
            Maximum progress display update interval [default: 10] seconds.
            Automatically adjusts `miniters` to correspond to `mininterval`
            after long display update lag. Only works if `dynamic_miniters`
            or monitor thread is enabled.
        miniters  : int, optional
            Minimum progress display update interval, in iterations.
            If 0 and `dynamic_miniters`, will automatically adjust to equal
            `mininterval` (more CPU efficient, good for tight loops).
            If > 0, will skip display of specified number of iterations.
            Tweak this and `mininterval` to get very efficient loops.
            If your progress is erratic with both fast and slow iterations
            (network, skipping items, etc) you should set miniters=1.
        ascii  : bool or str, optional
            If unspecified or False, use unicode (smooth blocks) to fill
            the meter. The fallback is to use ASCII characters " 123456789#".
        disable  : bool, optional
            Whether to disable the entire progressbar wrapper
            [default: False]. If set to None, disable on non-TTY.
        unit  : str, optional
            String that will be used to define the unit of each iteration
            [default: it].
        unit_scale  : bool or int or float, optional
            If 1 or True, the number of iterations will be reduced/scaled
            automatically and a metric prefix following the
            International System of Units standard will be added
            (kilo, mega, etc.) [default: False]. If any other non-zero
            number, will scale `total` and `n`.
        dynamic_ncols  : bool, optional
            If set, constantly alters `ncols` to the environment (allowing
            for window resizes) [default: False].
        smoothing  : float, optional
            Exponential moving average smoothing factor for speed estimates
            (ignored in GUI mode). Ranges from 0 (average speed) to 1
            (current/instantaneous speed) [default: 0.3].
        bar_format  : str, optional
            Specify a custom bar string formatting. May impact performance.
            [default: '{l_bar}{bar}{r_bar}'], where
            l_bar='{desc}: {percentage:3.0f}%|' and
            r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
              '{rate_fmt}{postfix}]'
            Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
              percentage, rate, rate_fmt, rate_noinv, rate_noinv_fmt,
              rate_inv, rate_inv_fmt, elapsed, elapsed_s, remaining,
              remaining_s, desc, postfix, unit.
            Note that a trailing ": " is automatically removed after {desc}
            if the latter is empty.
        initial  : int, optional
            The initial counter value. Useful when restarting a progress
            bar [default: 0].
        position  : int, optional
            Specify the line offset to print this bar (starting from 0)
            Automatic if unspecified.
            Useful to manage multiple bars at once (eg, from threads).
        postfix  : dict or *, optional
            Specify additional stats to display at the end of the bar.
            Calls `set_postfix(**postfix)` if possible (dict).
        unit_divisor  : float, optional
            [default: 1000], ignored unless `unit_scale` is True.
        write_bytes  : bool, optional
            If (default: None) and `file` is unspecified,
            bytes will be written in Python 2. If `True` will also write
            bytes. In all other cases will default to unicode.
        gui  : bool, optional
            WARNING: internal parameter - do not use.
            Use tqdm_gui(...) instead. If set, will attempt to use
            matplotlib animations for a graphical output [default: False].

更多功能则可根据以上参数发挥你的想象力了。

参考资料

[1] tqdm官网: https://pypi.org/project/tqdm/

[2] time: https://www.runoob.com/linux/linux-comm-time.html

[3] find: https://www.runoob.com/linux/linux-comm-find.html

[4] wc: https://www.runoob.com/linux/linux-comm-wc.html

相关推荐

python爬取电子课本,送给居家上课的孩子们

在这个全民抗疫的日子,中小学生们也开启了居家上网课的生活。很多没借到书的孩子,不得不在网上看电子课本,有的电子课本是老师发的网络链接,每次打开网页去看,既费流量,也不方便。今天我们就利用python的...

高效办公!Python 批量生成PDF文档是如何做到的?

前言:日常办公中,经常会使用PDF文档,难免需要对PDF文档进行编辑,有时候PDF文档中的大部分内容都是一样的,只是发送对象不同。这种模板套用的场景下,使用Python进行自动化就尤为方便,用最短的时...

如何用Python将PDF完整的转成Word?

PDF文件完整的转为Word,转换后格式排版不会乱,图片等信息完整显示不丢失。这个很简单,有很多方法都可以实现。方法一:Python利用Python将PDF文件转换为Word,有许多库可以帮你实现这一...

使用Python拆分、合并PDF(python合并多个pdf)

知识点使用Python操作PDF!主要内容有:1、PDF拆分;2、PDF合并。在工作中,难免会和PDF打交道,所以掌握一点处理PDF的技能非常有必要,本文将介绍几个常用的功能。PDF拆分很多时候,获取...

10分钟实现PDF转Word神器!看DeepSeek如何用Python解放打工人

开篇痛点每个被PDF折磨过的职场人都懂——领导发来的扫描件要修改,手动抄到Word需要2小时;网上下载的报告想复制数据,却变成乱码…今天我们用Python+DeepSeek,10分钟打造一个智能转换工...

《Python知识手册》,高清全彩pdf版开放下载

Python编程还不懂?今天我要把我参与编写的这套《Python知识手册》免费分享出来,看完文末有惊喜哦。...

利用python进行数据分析,PDF文档给你答案

本书详细介绍利用Python进行操作、处理、清洗和规整数据等方面的具体细节和基本要点。虽然本书的标题是“数据分析”,重点却是Python编程、库,以及用于数据分析的工具。兄弟,毫无套路!PDF版无偿获...

OCRmypdf:一款可以让扫描PDF文件变得可搜索、可复制!

简介在日常工作中,我们经常会接触到各种PDF文件,其中不少是扫描版文档。处理这些扫描PDF时,尽管内容看似完整,但往往无法直接复制或搜索其中的文本。尤其是在需要对大量文档进行文本分析、存档或后期编辑时...

高效的OCR处理工具!让扫描PDF文件变得可搜索、可复制!

在工作中,我们常常遇到各种各样的PDF文件,其中不乏一些扫描版的文档。而在处理扫描的PDF文件时,虽然文件内容看似完整,但你却无法复制、搜索其中的文本。特别是对大量文档需要进行文本分析、存档、或者...

三步教你用Elasticsearch+PyMuPDF实现PDF大文件秒搜!

面对100页以上的大型PDF文件时,阅读和搜索往往效率低下。传统关系型数据库在处理此类数据时容易遇到性能瓶颈,而Elasticsearch凭借其强大的全文检索和分布式架构,成为理想解决方案。通过...

用 Python 去除 PDF 水印,你学会吗?

今天介绍下用Python去除PDF(图片)的水印。思路很简单,代码也很简洁。首先来考虑Python如何去除图片的水印,然后再将思路复用到PDF上面。这张图片是前几天整理《数据结构和算法...

扫描PDF档案效率提升300%!OCRmyPDF:告别无法搜索的PDF噩梦,这款26K Star的开源神器让文本识别轻松上手!

要在PDF中搜索某个关键词,结果发现啥也找不到?这种情况大多数人都遇到过吧,特别是处理扫描文档或图片PDF时。就在前几天,我还在为这事抓狂呢!后来无意中发现了OCRmyPDF这个宝藏项目...简直就...

Python自动化办公之PDF版本发票识别并提取关键信息教程(上篇)

大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Python自动化办公发票数据处理的问题,一起来看看吧。二、实现过程这个问题在实际工作中还是非常常见的,实用性和通用性都比...

PDF解锁神器:用PyMuPDF与pdfplumber告别手动提取

前言大家好,今天咱们来聊聊如何用Python中的PyMuPDF和pdfplumber库,轻松提取PDF文件里的文本和元数据。你是否曾经在处理一个复杂的PDF文件时,感到信息难以触及,提取过程让人抓狂?...

《Python知识手册》,高清pdf免费获取

今天我要把我参与编写的这套《Python知识手册》免费分享出来,真正弘扬Python开源精神!手册的部分页面如下:获取方式:...

取消回复欢迎 发表评论: