Vas*_*ily 4 python python-3.x progress-bar
我的pyhton3脚本使用urlretrieve通过Internet下载了许多图像,我想为每个下载添加进度条,其中包含完成的百分比和下载速度。
该进度模块似乎是一个很好的解决方案,不过虽然我已经通过看他们的榜样和范例4似乎是正确的事情,我仍然无法理解如何将它环绕的urlretrieve。
我想我应该添加第三个参数:
urllib.request.urlretrieve('img_url', 'img_filename', some_progressbar_based_reporthook)
Run Code Online (Sandbox Code Playgroud)
但是如何正确定义呢?
我认为更好的解决方案是创建一个具有所有所需状态的类
class MyProgressBar():
def __init__(self):
self.pbar = None
def __call__(self, block_num, block_size, total_size):
if not self.pbar:
self.pbar=progressbar.ProgressBar(maxval=total_size)
self.pbar.start()
downloaded = block_num * block_size
if downloaded < total_size:
self.pbar.update(downloaded)
else:
self.pbar.finish()
Run Code Online (Sandbox Code Playgroud)
并致电:
urllib.request.urlretrieve('img_url', 'img_filename', MyProgressBar())
Run Code Online (Sandbox Code Playgroud)
对于我来说,其他答案中的建议没有超过1%。这是在Python 3上对我有用的完整实现:
import progressbar
import urllib.request
pbar = None
def show_progress(block_num, block_size, total_size):
global pbar
if pbar is None:
pbar = progressbar.ProgressBar(maxval=total_size)
downloaded = block_num * block_size
if downloaded < total_size:
pbar.update(downloaded)
else:
pbar.finish()
pbar = None
urllib.request.urlretrieve(model_url, model_file, show_progress)
Run Code Online (Sandbox Code Playgroud)