• python加入进度条:tqdm 和 progressbar


    这里主要是有两个方法:tqdm 和 progressbar

    1. 首先是tqdm方法:

    from time import sleep
    from tqdm import tqdm
    
    for i in tqdm(range(10)):
       # 需要循环或者多次执行的代码
       print('
     the value of i is %d ---'%i)  #正常的整数值:i
       for ii in range(i):
           print(ii)
       sleep(0.1)

    • tqdm显示进度条解释:注意参数不一定要是数字,可迭代对象即可
    from tqdm import tqdm
    import time
    
    for ss in tqdm(range(10)):
        time.sleep(10)
        print('this is test for tqdm with:',ss)
    
    list_ = ['高楼','湖水','大海']  #可迭代对象即可,不一定要数字
    for ss in tqdm(list_):
        time.sleep(10)
        print('this is test for tqdm with:', ss)

    可以很明显看到:

    (1)想看进度,直接看百分比即可,表示完成了多少,例如80%,当然也可以看分数8/10。

    (2)第一个时间表示已经执行的时间,第二个时间表示还剩多少时间。

    (3)速度:s/it,表示每次迭代需要的时间。

    • tqdm函数定义和部分参数
     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, gui=False, **kwargs):
            """
            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. 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.
    ......
            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, remaining, desc, postfix.
                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).
    ......

    使用示例:

    list_ = ['高楼','湖水','大海']
    for ss in tqdm(list_, desc='---', postfix='***'):
        time.sleep(10)
        print('this is test for tqdm with:', ss)

    4. 其次是progressbar方法

    from progressbar import ProgressBar, Percentage, Bar, Timer, ETA, FileTransferSpeed
    
    aa = [1,2,3,4,5,6,7,8,9]
    total = len(aa)
    
    def dowith_i(i):
        for ii in range(i):  
            print(ii)
            sleep(0.1)
     
    widgets = ['当前进度: ',Percentage(), ' ', Bar('=>'),' ', Timer(),
               ' ', ETA(), ' ', FileTransferSpeed()]
    bar_object = ProgressBar(widgets=widgets, maxval=10*total).start()
    for i in range(total):
        print('
    ')
        dowith_i(i)  #做自己的任务
        bar_object.update(10 * i + 1)
    bar_object.finish()

     其中 'widgets' 参数可以自己设置。

    Timer:表示经过的秒(时间)

    Bar:设置进度条形状

    Percentage:显示百分比进度

    ETA:预估剩余时间

    FileTransferSpeed:文件传输速度

    参考:

    https://baijiahao.baidu.com/s?id=1604219346207216803&wfr=spider&for=pc

    https://blog.csdn.net/dcrmg/article/details/79525167

  • 相关阅读:
    FastAPI数据库系列(一) MySQL数据库操作
    FastAPI响应系列(二) 响应状态码
    FastAPI系列学习目录
    FastAPI大型目录程序设计
    FastAPI异步任务系列(一) FastAPI后台任务
    FastAPI安全系列(三) 基于Hash Password和JWT Bearer Token的OAuth2 .0认证
    FastAPI安全系列(二) 基于Password和Bearer Token的OAuth2 .0认证
    FastAPI安全系列(一) OAuth2 .0认证基础
    you can run: npm install --save core-js/modules/es.regexp.exec core-js/modules/es.string.replace(已解决)
    BFC总结
  • 原文地址:https://www.cnblogs.com/qi-yuan-008/p/12125197.html
Copyright © 2020-2023  润新知