最近需要用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 是一個快速,可擴展的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()
# !/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.
find . -name '*.py' -exec cat \{} \; |
tqdm --unit loc --unit_scale --total 857366 >> /dev/null
以上就是python實現進度條功能的一些功能實現了。