前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python实现进度条功能

python实现进度条功能

作者头像
测试加
发布2022-06-21 16:18:22
1.2K0
发布2022-06-21 16:18:22
举报

背景

最近需要用python写一个小脚本"实现进度条功能",用到了一些小知识,赶紧抽空记录一下。不深但是常用。

原生方式

两个进度条示例,拷贝就能运行:

Demo代码如下:

代码语言:javascript
复制
# coding=utf-8

import sys
import time

# width:宽度,   percent:百分比
def progress(width, percent):
    print "\r%s %d%%" % (('%%-%ds' % width) % (width * percent / 100 * '='), percent),
    if percent >= 100:
        print
        sys.stdout.flush()


# 示例一、0%--100%
def demo1():
    for i in xrange(100):
        progress(50, (i + 1))
        time.sleep(0.1)


##  示例二、周期加载
def demo2():
    i = 19
    n = 200
    while n > 0:
        print "\t\t\t%s \r" % (i * "="),
        i = (i + 1) % 20
        time.sleep(0.1)
        n -= 1


demo1()
demo2()

提供一个自己写的一个简单异步进度条,可以在耗时操作前开启,然后再耗时操作结束后停止。

Demo代码如下:

代码语言:javascript
复制
import time
import thread
import sys

class Progress:
    def __init__(self):
        self._flag = False
    def timer(self):
        i = 19
        while self._flag:
            print "\t\t\t%s \r" % (i * "="),
            sys.stdout.flush()
            i = (i + 1) % 20
            time.sleep(0.05)
        print "\t\t\t%s\n" % (19 * "="),
        thread.exit_thread()
    def start(self):
        self._flag = True
        thread.start_new_thread(self.timer, ())
    def stop(self):
        self._flag = False
        time.sleep(1)

progress = Progress()
progress.start()
time.sleep(5)
progress.stop()        

以上两个代码实现进度条功能,用到了python基础就可以实现,但是扩展性和易用性不太好。 下面我们看看其他第三方库如何实现该功能~

tqdm

简介

Tqdm 是一个快速,可扩展的Python进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器 tqdm(iterator)。

安装

代码语言:javascript
复制
pip install tqdm

案例一

代码语言:javascript
复制
#!/usr/local/bin/python
# -*- coding:utf-8 -*-

import time
from tqdm import tqdm
from tqdm._tqdm import trange

for i in tqdm(range(100)):
    time.sleep(0.01)

案例二

对于任意list的使用

代码语言:javascript
复制
#!/usr/local/bin/python
# -*- coding:utf-8 -*-

import time
from tqdm import tqdm
from tqdm.std import trange

alist = list('letters-demo')
bar = tqdm(alist)
for letter in bar:
    bar.set_description(f"Now get {letter}")

案例三

代码语言:javascript
复制
with tqdm(total=100) as pbar:
    for i in range(10):
        pbar.update(10)


# 也可以这样
pbar = tqdm(total=100)
for i in range(10):
    pbar.update(10)
pbar.close()

案例四(下载mp3)

代码语言:javascript
复制
# !/usr/local/bin/python
# -*- coding:utf-8 -*-

from tqdm import tqdm
import time, requests


def downloadFILE(url, name):
    resp = requests.get(url=url, stream=True)
    content_size = int(resp.headers['Content-Length']) / 1024
    with open(name, "wb") as f:
        print("Pkg total size is:", content_size, 'k,start...')
        for data in tqdm(iterable=resp.iter_content(1024), total=content_size, unit='k', desc=name):
            f.write(data)
        print(name + "download finished!")


if __name__ == '__main__':
    url = "https://music.163.com/song/media/outer/url?id=1465245956.mp3"
    name = 'good-mp3'
    downloadFILE(url, name)

命令行

查看参数

tqdm --help

代码语言:javascript
复制
--unit=<unit>  : str, optional
            String that will be used to define the unit of each iteration

--unit-scale=<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`. 

--total=<total>  : int or float, 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 number,
    e.g. 9e9.        
查询py文件
代码语言:javascript
复制
find . -name '*.py' -exec cat \{} \; |
    tqdm --unit loc --unit_scale --total 857366 >> /dev/null

结语

以上就是python实现进度条功能的一些功能实现了。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-05-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 测试加 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 背景
    • 原生方式
      • tqdm
        • 简介
        • 安装
        • 案例一
        • 案例二
        • 案例三
        • 案例四(下载mp3)
        • 命令行
      • 结语
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档