天天看點

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

複制

python實作進度條功能背景

提供一個自己寫的一個簡單異步進度條,可以在耗時操作前開啟,然後再耗時操作結束後停止。

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)
           

複制

python實作進度條功能背景

案例二

對于任意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).
    If `gui` is True and this parameter needs subsequent updating,
    specify an initial arbitrary large positive number,
    e.g. 9e9.        
           

複制

python實作進度條功能背景

查詢py檔案

find . -name '*.py' -exec cat \{} \; |
    tqdm --unit loc --unit_scale --total 857366 >> /dev/null
           

複制

python實作進度條功能背景

結語

以上就是python實作進度條功能的一些功能實作了。