前言

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

1 简单了解

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

tqdm运行

相关代码如下:

import tqdm

import time

foriintqdm.tqdm(range(1000)):

time.sleep(0.1)

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

run2

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

2 使用

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

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

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

fromtqdm import tqdm

fromtimeimport sleep

text = ""

forcharintqdm(["a","b","c","d"]):

sleep(0.25)

text = text + char

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

fromtimeimport sleep

fromtqdm import trange

foriintrange(100):

sleep(0.01)

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

pbar = tqdm(["a","b","c","d"])

forcharinpbar:

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的更新,可以根据具体任务来更新进度条的进度。

withtqdm(total=100)aspbar:

foriinrange(10):

sleep(0.1)

pbar.update(10)

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

pbar = tqdm(total=100)

foriinrange(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打开),也是当前项目路径。

timefind . -name'*.py'-type f -execcat \{} \; | wc -l

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

使用tqdm命令来试一试:

timefind . -name'*.py'-type f -execcat \{} \; | tqdm | wc -l

则有:

tqdm

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

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

3 参数

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

class tqdm():

"""

Decorate an iterable object, returning an iterator which acts exactly

likethe original iterable, but prints a dynamically updating

progressbar every timea valueisrequested.

"""

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 todecoratewitha progressbar.

Leave blank tomanually manage the updates.

desc: str, optional

Prefix forthe progressbar.

total  : int, optional

The number ofexpected iterations. If unspecified,

len(iterable) isused if possible. Iffloat("inf")orasalast

resort, onlybasic progressstatisticsare displayed

(noETA,noprogressbar).

If `gui` isTrueandthis parameter needs subsequent updating,

specify an initial arbitrary large positive integer,

e.g. int(9e9).

leave  : bool, optional

If [default:True], keepsalltracesofthe progressbar

upon termination ofiteration.

file  : `io.TextIOWrapper` or`io.StringIO`, optional

Specifies wheretooutputthe progress messages

(default: sys.stderr). Uses `file.write(str)`and`file.flush()`

methods.  Forencoding, see `write_bytes`.

ncols  : int, optional

The width ofthe entireoutputmessage. If specified,

dynamically resizes the progressbar tostay within this bound.

If unspecified, attempts touse environment width. The

fallback isa meter widthof10andnolimitforthe counterand

statistics. If 0, willnotprintanymeter (onlystats).

mininterval  : float, optional

Minimum progress display updateinterval [default: 0.1] seconds.

maxinterval  : float, optional

Maximum progress display updateinterval [default: 10] seconds.

Automatically adjusts `miniters` tocorrespondto`mininterval`

afterlong displayupdatelag.Onlyworks if `dynamic_miniters`

ormonitor threadisenabled.

miniters  : int, optional

Minimum progress display updateinterval,initerations.

If 0 and`dynamic_miniters`, will automatically adjusttoequal

`mininterval` (more CPU efficient, good fortight loops).

If > 0, will skip display ofspecified numberofiterations.

Tweak this and`mininterval`toget very efficient loops.

If your progress iserraticwithboth fastandslow iterations

(network, skipping items, etc) you should setminiters=1.

ascii  : bool orstr, optional

If unspecified orFalse, use unicode (smooth blocks)tofill

the meter. The fallback istouse ASCII characters" 123456789#".

disable  : bool, optional

Whether todisable the entire progressbar wrapper

[default:False]. IfsettoNone, disableonnon-TTY.

unit  : str, optional

String that will be used todefine the unitofeach iteration

[default: it].

unit_scale  : bool orintorfloat, optional

If 1 orTrue, the numberofiterations will be reduced/scaled

automatically anda metric prefix following the

International System ofUnits standard will be added

(kilo, mega, etc.) [default:False]. Ifanyother non-zero

number, will scale `total` and`n`.

dynamic_ncols  : bool, optional

If set, constantly alters `ncols`tothe environment (allowing

forwindow resizes) [default:False].

smoothing  : float, optional

Exponential moving average smoothing factor forspeed estimates

(ignored inGUI mode). Rangesfrom0 (average speed)to1

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

'{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 ": "isautomatically removedafter{desc}

if the latter isempty.

initial  : int, optional

The initial counter value. Useful whenrestarting a progress

bar [default: 0].

position  : int, optional

Specify the line offset toprint this bar (startingfrom0)

Automatic if unspecified.

Useful tomanage multiple barsatonce (eg,fromthreads).

postfix  : dict or*, optional

Specify additional stats todisplayattheendofthe bar.

Calls `set_postfix(**postfix)` if possible (dict).

unit_divisor  : float, optional

[default: 1000], ignored unless `unit_scale`isTrue.

write_bytes  : bool, optional

If (default: None)and`file`isunspecified,

bytes will be written inPython 2. If `True` will also write

bytes. Inallother cases willdefaulttounicode.

gui  : bool, optional

WARNING: internal parameter - do notuse.

Use tqdm_gui(...) instead. Ifset, will attempttouse

matplotlib animations fora graphicaloutput[default:False].

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

【责任编辑:未丽燕 TEL:(010)68476606】

点赞 0

python 进度条 tqdm_Python进度条tqdm,你值得拥有相关推荐

  1. html video显示进度条_使用 tqdm 在 Python 应用中显示进度 | Linux 中国

    如果你的程序需要一段时间才能显示结果,可通过显示它的进度来避免让用户感到沮丧. 来源:https://linux.cn/article-12990-1.html 作者:Moshe Zadka 译者:g ...

  2. 给 Python 添加进度条 | 给小白的 tqdm 精炼实例!

    给 Python 添加进度条 | 给小白的 tqdm 精炼实例! 假设我们有一个循环: for i in range(100):do_something() # 这里做某些事 假设 do_someth ...

  3. python 进度条_python进度条

    广告关闭 云服务器1核2G首年99年,还有多款热门云产品满足您的上云需求 功能说明:将程序执行进展情况按照百分比用进度条显示,适合用于文件传输进度显示运行环境:linux 6,python3. 6. ...

  4. Python中4种进度条的使用方法

    如果你之前没用过进度条,八成是觉得它会增加不必要的复杂性或者很难维护,其实不然.要加一个进度条其实只需要几行代码.在这几行代码中,我们可以看看如何在命令行脚本以及 PySimpleGUI UI 中添加 ...

  5. Python如何在控制台显示进度条

    我们在写一些python程序时,如果程序运行时间较长,我们希望能够有一个进度条来动态的展示程序运行进度. 首先能想到的做法是用print将执行到第几步打印出来,但这样显然不是我们想要的进度条,显示进度 ...

  6. python gui下载进度条_对python GUI实现完美进度条的示例详解

    在用python做一个gui界面时,想搞一个进度条实时显示下载进度,但查阅很多博客,最后的显示效果都类似下面这种: 这种效果在cmd界面看着还可以,但放到图形界面时就有点丑了,所以我用canvas重新 ...

  7. 【Python笔记】pyqt5进度条-多线程图像分块处理防止窗体卡顿

    目录 主要功能 环境配置 实现过程 1.设计ui 主界面 弹出框 窗体文件 2.主体实现 打开文件 计算函数 代码附录 title.ui titleok.ui title.py titleok.py ...

  8. Android小项目之--前台界面与用户交互的对接 进度条与拖动条(附源码)

    都知道水果公司(苹果)是己尊重用户体验著称的公司,其设计的产品人性化十足,不得不令后来者赞叹,竞相模仿.iphone的成功就是其典型的案例,做为其移动系统的死对头 Google 想要在市场上分得一杯羹 ...

  9. 疯狂JAVA讲义---第十二章:Swing编程(五)进度条和滑动条

    http://blog.csdn.net/terryzero/article/details/3797782 疯狂JAVA讲义---第十二章:Swing编程(五)进度条和滑动条 标签: swing编程 ...

最新文章

  1. Linux Shell中的延时函数
  2. 计算机乐谱弱点,缺点简谱郑源
  3. Tyznn人脸识别温度检测智能门禁系统现货发售,助力疫情防控
  4. crontab 详细用法 定时任务
  5. github --- 多个项目的管理方式
  6. java 设置不可点击_Java Selenium webdriverwait 解决元素不可点击问题
  7. 算法竞赛从入门到进阶pdf_【算法趣谈】线段树 从入门到进阶
  8. 神经网络控制器设计原理,神经网络控制系统设计
  9. 中兴面试题 01背包问题
  10. 《G档案》中关于游戏程序设计的文章
  11. Ambari 安装多个impala deamon节点(apache impala)
  12. 新巴巴运动网项目需求书_巴巴姆少儿英语项目介绍(613岁)
  13. 用js写卡牌游戏(四)
  14. python神经网络预测股票组合_神经网络预测股票市场
  15. 目录-Amira用户指南
  16. 泰安链底层系统设计、核心优势、技术实现
  17. Android webview和HTML的JS交互
  18. 在IDEA中写Python
  19. openGauss 简介
  20. 杰理芯片移植涂鸦OTA步骤

热门文章

  1. 速达数据库服务器密码修改,如何创建SQL数据库登录用户及密码? 找昆明速达软件...
  2. 卫生统计学第2版_卫生统计学计算机操作教程(第2版)
  3. 专属于通信人的情诗--情书
  4. Artifact has not been packaged yet. When used on reactor artifact.....see MDEP-187
  5. 分布式系统基础架构hadoop搭建
  6. 分组求和,将一列的数据求和
  7. 5G丨CTIA:中美领跑“全球5G竞赛” 韩国紧随其后
  8. linux安装微信和qq
  9. 教师布置作业给学生和家长-Java
  10. Qgis开发5-完整的Qgis系统库——qis_app库