Need to use... Recently python Write a small script " Realize the function of progress bar ", Used some small knowledge , Take time to record . Not deep but often used .
Two progress bar examples , Copy can run :
Demo The code is as follows :
# coding=utf-8
import sys
import time
# width: Width , percent: percentage
def progress(width, percent):
print "\r%s %d%%" % (('%%-%ds' % width) % (width * percent / 100 * '='), percent),
if percent >= 100:
print
sys.stdout.flush()
# Example 1 、0%--100%
def demo1():
for i in xrange(100):
progress(50, (i + 1))
time.sleep(0.1)
## Example 2 、 Periodic loading
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()
Provide a simple asynchronous progress bar written by yourself , It can be turned on before the time-consuming operation , Then stop after the time-consuming operation .
Demo The code is as follows :
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()
The above two codes realize the progress bar function , Yes python Foundation can be realized , But the scalability and ease of use are not very good . Let's take a look at how other third-party libraries implement this function ~
Tqdm It's a fast one , Extensible Python Progress bar , Can be in Python Add a progress prompt to the long loop , Users only need to encapsulate any iterator 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)
For any list Use
#!/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)
# You can do that
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
That's all python Some functions of the progress bar function are realized .