相关文章推荐
谦和的牙膏  ·  module 'numpy' has no ...·  1 周前    · 
会搭讪的花卷  ·  飞猪 - 开放平台·  1 年前    · 
坚强的山楂  ·  PHP 运算符 | 菜鸟教程·  1 年前    · 
python实现进度条功能

python实现进度条功能

背景

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



原生方式

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

Demo代码如下:

# 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代码如下:

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)。

安装

pip install tqdm

案例一

#!/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的使用

#!/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}")

案例三

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)

# !/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

--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).