tqdm

在看别人写的代码的时候发现的tqdm模块,当时还很好奇,这命名不像是标准库函数,于是乎去搜索了一下,是一个显示进度条的库

演示

试看如下代码:

from tqdm import tqdm
from time import sleep
for i in tqdm(range(0, 100), desc="加载中", colour="green"):sleep(1)
加载中:  70%|███████   | 70/100 [01:10<00:30,  1.01s/it]

当时第一次看得时候不太理解 01:10<00:30 这种显示方式,对此感到非常的不舒服,想要调整一下格式,去网上搜了搜tqdm的教程,发现清一色都是tqdm(range()),事实上和官方提供的大同小异,官方文档提供的例子更为丰富一些。

多次查找无果后,深感自己阅读文档的水平不足。

提高

为了解决 01:10<00:30 这个问题,忽而记起网上对tqdm库的描述,这是个纯python实现的库。点进去看源码,文件名std.py。

    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, write_bytes=None,lock_args=None, nrows=None, colour=None, delay=0, gui=False,**kwargs):"""Parameters----------iterable  : iterable, optionalIterable to decorate with a progressbar.Leave blank to manually manage the updates.desc  : str, optionalPrefix for the progressbar.total  : int or float, optionalThe number of expected iterations. If unspecified,len(iterable) is used if possible. If float("inf") or as a lastresort, 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 number,e.g. 9e9.leave  : bool, optionalIf [default: True], keeps all traces of the progressbarupon termination of iteration.If `None`, will leave only if `position` is `0`.file  : `io.TextIOWrapper` or `io.StringIO`, optionalSpecifies where to output the progress messages(default: sys.stderr). Uses `file.write(str)` and `file.flush()`methods.  For encoding, see `write_bytes`.ncols  : int, optionalThe width of the entire output message. If specified,dynamically resizes the progressbar to stay within this bound.If unspecified, attempts to use environment width. Thefallback is a meter width of 10 and no limit for the counter andstatistics. If 0, will not print any meter (only stats).mininterval  : float, optionalMinimum progress display update interval [default: 0.1] seconds.maxinterval  : float, optionalMaximum 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 or float, optionalMinimum 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, optionalIf unspecified or False, use unicode (smooth blocks) to fillthe meter. The fallback is to use ASCII characters " 123456789#".disable  : bool, optionalWhether to disable the entire progressbar wrapper[default: False]. If set to None, disable on non-TTY.unit  : str, optionalString that will be used to define the unit of each iteration[default: it].unit_scale  : bool or int or float, optionalIf 1 or True, the number of iterations will be reduced/scaledautomatically and a metric prefix following theInternational System of Units standard will be added(kilo, mega, etc.) [default: False]. If any other non-zeronumber, will scale `total` and `n`.dynamic_ncols  : bool, optionalIf set, constantly alters `ncols` and `nrows` to theenvironment (allowing for window resizes) [default: False].smoothing  : float, optionalExponential 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, optionalSpecify a custom bar string formatting. May impact performance.[default: '{l_bar}{bar}{r_bar}'], wherel_bar='{desc}: {percentage:3.0f}%|' andr_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ''{rate_fmt}{postfix}]'Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,rate, rate_fmt, rate_noinv, rate_noinv_fmt,rate_inv, rate_inv_fmt, postfix, unit_divisor,remaining, remaining_s, eta.Note that a trailing ": " is automatically removed after {desc}if the latter is empty.initial  : int or float, optionalThe initial counter value. Useful when restarting a progressbar [default: 0]. If using float, consider specifying `{n:.3f}`or similar in `bar_format`, or specifying `unit_scale`.position  : int, optionalSpecify 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 *, optionalSpecify 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, optionalIf (default: None) and `file` is unspecified,bytes will be written in Python 2. If `True` will also writebytes. In all other cases will default to unicode.lock_args  : tuple, optionalPassed to `refresh` for intermediate output(initialisation, iterating, and updating).nrows  : int, optionalThe screen height. If specified, hides nested bars outside thisbound. If unspecified, attempts to use environment height.The fallback is 20.colour  : str, optionalBar colour (e.g. 'green', '#00ff00').delay  : float, optionalDon't display until [default: 0] seconds have elapsed.gui  : bool, optionalWARNING: internal parameter - do not use.Use tqdm.gui.tqdm(...) instead. If set, will attempt to usematplotlib animations for a graphical output [default: False].

以往看一些源码都是一堆说明然后写个pass,这种实现方式一般都是使用c语言实现的,源码看起来会比较麻烦。而纯python实现的那可太好了。

bar_format 这个参数,想来就是我想要的了,看一下注释里bar_format的描述 default: ‘{l_bar}{bar}{r_bar}’,试了试就理解了这三个参数的意义,很可惜的是依然不能解决我的问题。

再深入往里看,r_bar这个参数引起了我的注意,这应该就是我关注的部分了。随后找到format_meter函数,找到如下代码:

r_bar = '| {0}/{1} [{2}<{3}, {4}{5}]'.format(n_fmt, total_fmt, elapsed_str, remaining_str, rate_fmt, postfix)

至此算是完了,但又没完。我翻遍整个std.py文件,没找到单独设置r_bar的地方,有的只是bar_format,换句话说就是原作者并没有对这个进行支持,所以无可奈何。除了直接修改tqdm源码,暂时没有想到更简单的办法,有些遗憾。

结语

对于纯python的第三方库,感到极其亲切,不像是底层c语言实现的一些标准库,看到一个空函数,一堆文字描述加上pass,实在是感到沮丧。直接阅读代码比阅读文档的方式可能来得更直接易于理解,仅仅是对于我而已,仅仅限制在对于tqdm库而言。

通常都是直接找官方文档,阅读源码的方式也不失为一种很好的办法,这种交流更为直接,明晰。

更新

对源码的理解不够深入

自定义进度条

from time import sleepfrom tqdm import tqdmtqdm_iter = tqdm(range(0,100),desc="loading",colour="green",bar_format="{l_bar}{bar}|[用时:{elapsed} 还剩:{remaining}]")for i in tqdm_iter:sleep(0.1)

Python 第三方库 tqdm相关推荐

  1. 4行指令解决pip下载Python第三方库太慢问题(pip更换国内下载源)

     问题由来: 之前在写一篇项目博客时,pip下载Python第三方库:graphic-verification-code,实在太慢了,于是使用Python库官网下载,还是很慢,而且不断失败,下载慢且不 ...

  2. dos系统不能安装python模块,无法使用pip命令安装python第三方库的原因及解决方法...

    再dos中无法使用pip,命令主要是没有发现这个命令.我们先找到这个命令的位置,一般是在python里面的scripts文件夹里面.我们可以把dos切换到对应的文件夹,再使用pip命令就可以了. 如果 ...

  3. 查看本机中的python第三方库文档

    [转载] 原文链接:https://blog.csdn.net/weixin_43936250/article/details/105251049 本机系统为win10,在使用python编程的过程中 ...

  4. Python_note8 程序设计方法学+Python第三方库安装+os库

    实例13 体育竞技分析 自顶向下,解决复杂问题的有效方法,将一个小问题表达为若干小问题组成的形式,使用同样方法进一步解决小问题直至可以用计算机简单解决:自底向上 理解自顶向下的设计思维:分而治之:理解 ...

  5. 离线安装python第三方库的实用方法:解决公司内网,服务器/电脑不能上网却需要安装python三方库问题(上:Windows环境中)

    离线安装python第三方库的实用方法:解决公司内网,服务器/电脑不能上网却需要安装python三方库问题(上:Windows环境中) 参考文章: (1)离线安装python第三方库的实用方法:解决公 ...

  6. python如何离线安装第三方库_离线环境安装python第三方库

    python 离线环境安装python第三方库 author: yafeishi tags: AntDB,python python对于运维工作确实方便了很多,但很多比较实用的库都是第三方提供,在os ...

  7. 下面不属于python第三方库的安装方法的是-关于python中第三方库安装方法和问题解决...

    一.安装方法 方法一: 1.管理员身份启动命令行(运行--->cmd) 2.pip install 库的绝对路径和库的详细名称 :或者运用cd命令跳转到下载好的库所在的位置然后pip insta ...

  8. python中安装一个第三方库的命令格式是-无法使用pip命令安装python第三方库的彻底解决方案...

    无法使用pip命令安装python第三方库的原因及解决方法 再dos中无法使用pip,命令主要是没有发现这个命令.我们先找到这个命令的位置,一般是在python里面的Scripts文件夹里面.我们可以 ...

  9. python第三方库numpy-Python第三方库之openpyxl(2)

    Python第三方库之openpyxl(2) 简单的使用 写一个工作簿 >>> from openpyxl importWorkbook>>> from openp ...

最新文章

  1. Silverlight4 学习视频(四)
  2. 【PHPExcel】设置打印格式
  3. 决定系数 均方误差mse_回归模型评价指标 SSE, MSE、RMSE、MAE、R-SQUARED
  4. mllib调参 spark_从Spark MLlib到美图机器学习框架实践
  5. Oracle分析函数详述
  6. 重载session存储方式–session_set_save_handler()
  7. 大数据入门笔记(三)
  8. ab实验置信度_为什么您的Ab测试需要置信区间
  9. 从测试用例角度来看传统测试人员更专业?
  10. [C#基础]说说委托+=和-=的那些事
  11. 订单接收不同业务消息设计
  12. Atitit uke plnsy安全隐私保护法案 目录 第一章 一般规定 2 第1节 主题与目标 2 第二章 常见安全原则 3 第1节 隔离 保密 shell 3 第2节 隐藏 保密 不出头 3
  13. assign ur here php,ecshop源码分析01
  14. VirtualBox虚拟机安装教程
  15. 轻量型目标检测算法一次看个够
  16. 灌篮高手总决赛下载地址,都是pdf文件,黑白的,很清晰
  17. verdi 文件格式转换及差异
  18. 计算机网络和因特网笔记
  19. Android开发技巧!Android开发大佬的百度,美团,快手等大厂Offer收割之旅,附超全教程文档
  20. [java] int转byte的细节

热门文章

  1. 《计算机组装与维护》课程设计报告(二)
  2. [FROM WOJ]#4764 子矩阵
  3. vip服务器管理助手,[经济][VIP]VipZero —— 全自动出售道具会员[全版本]
  4. 计算机软件专业与甲骨文关系,基于本体的甲骨文专业文档语义标注方法-计算机应用与软件.PDF...
  5. Windows7优化提速完全宝典
  6. Ubuntu下FastDFS的安装
  7. windows bat批处理文件,实现某个软件的重启
  8. wps表格中文本框的边框怎么去掉?
  9. JSW Java_使用JSW包装你得Maven应用
  10. 4. Netty+SpringBoot实现IM服务 之 用户与channel绑定