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

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

off999 2024-09-14 07:15 71 浏览 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

相关推荐

应用商店安装包在哪儿(应用商店的安装)

你这样找很麻烦,打开360里面有个软件管家,打开进入后有个安装包管理,在那找找在文件管理器里面搜索apk格式的文件,如果有的话就可以搜到,没有的话就需要重新下载。oppo手机游戏中心里下载的东西在文件...

手机投屏到电脑win10(手机投屏到电脑windows7)

方法步骤:1.首先第一步我们打开电脑之后,点击开始菜单图标,在打开的界面中选择设置这个选项,点击打开Windows设置界面之后,进入到系统设置界面。 2.进入到系统设置界面之后,找到左边的投影到此电脑...

如何把ip地址改为美国(怎么把ip改为美国)

电脑是可以快速修改IP,不过需要IP修改工具来辅助修改的。很多工作室也需要这样的工具,他们大多是安装的{兔子IP}然后是全国IP随意使用的随意切换的。改变谷歌浏览器IP地址的步骤如下:1.在我们的电脑...

删除空白页word(删除空白页word一页怎么删)
删除空白页word(删除空白页word一页怎么删)

打开文档,选择空白页,再在键盘找到Delete键,单击即可。扩展资料产品功能文字新建Word文档功能支持.doc.docx.dot.dotx.wps.wpt文件格式的打开包括加密文档支持对文档进行查找替换、修订、字数统计、拼写检查等操作编辑...

2025-12-07 17:51 off999

最好看的中文字幕国语电影有哪些

1女尸谜案,又叫尸物招领,结局你绝对想不到,编剧是神2孤儿,(孤儿怨)这个简直是神作3婚纱,讲母女亲情的,超级感人,哭了一筐纸4告白,日本电影,通过几个人的自诉构成电影。拍摄的手法很特别5被嫌...

win7bios设置硬盘启动(win7硬盘启动顺序怎么设置)
  • win7bios设置硬盘启动(win7硬盘启动顺序怎么设置)
  • win7bios设置硬盘启动(win7硬盘启动顺序怎么设置)
  • win7bios设置硬盘启动(win7硬盘启动顺序怎么设置)
  • win7bios设置硬盘启动(win7硬盘启动顺序怎么设置)
电脑开机只显示字母无法进入

1.首先按Ctrl键、Shift键和Delete键重新启动电脑。2.然后按F8进入安全模式,使用安全卫士之类的软件对电脑进行一些清除。3.如果不行的话可以插入u盘,以u盘的模式启动进入Pe系统,然后重...

win10自带清理垃圾在哪(win10自带的清理)

Win十自带的安全软件可以清除垃圾,这是自带安全软件的最基本功能,WINDOWS系统主板安装完毕后,系统会自带一部分软件出现在电脑,最常见的有自带的安全软件,它除了可以巡检,是否有病毒木马等出现,还会...

怎样给电脑一键还原(怎样把电脑一键还原)

电脑一键还原恢复出厂的设置步骤:1,点击设置,进入windows系统后点击开始菜单,选择设置选项。2,选择恢复,点击更新和安全选项,在左边的列表中点击恢复选项。3,选择删除所有内容,找到重置此电脑下功...

苹果手机系统安装(苹果手机系统安装软件)

苹果手机在软件更新的功能内就可以进行系统更新。操作步骤如下: 1.点击设置的图标 2.选择通用的选项 3.点击软件更新的选项进入 4.在这里会检查手机的系统更新...

win10万能激活工具(win10万能激活码)

如果您购买了Windows10正版,可以使用以下步骤进行激活:1.打开“设置”:点击开始菜单,选择“设置”。2.进入“更新和安全”选项卡:在设置页面中,找到并点击“更新和安全”。3.进入“激活...

手机怎么添加桌面图标(苹果手机怎么添加桌面图标)

手机桌面添加图标方法1.打开应用程序列表,并长按需要添加桌面图标的应用程序。2.拖动应用程序到手机屏幕的任意位置,会自动出现图标。3.如果你需要添加更多的应用程序,可以重复上述步骤。4.如果你...

电脑开机密码怎么改换(电脑开机密码怎么改换不了)

在保证账户安全的前提下,您可以通过以下步骤来修改Windows操作系统的开机密码:1.登录到您的Windows账户:使用现有密码登录到计算机上的Windows系统。2.打开“控制面板”...

笔记本电脑无声音如何恢复正常
  • 笔记本电脑无声音如何恢复正常
  • 笔记本电脑无声音如何恢复正常
  • 笔记本电脑无声音如何恢复正常
  • 笔记本电脑无声音如何恢复正常
苹果手机真伪查询序列号(苹果手机查序列号辨真伪)

1.打开苹果官网:http://www.apple.com.cn/并点击页面右上角的技术支持选项。2.选择您要查询的设备比如说您要查询iPhone的话就选择iPhone。3.在iPhone的技术支持页...

取消回复欢迎 发表评论: