如何查看下载过程?
Posted
技术标签:
【中文标题】如何查看下载过程?【英文标题】:How to see the downloading process? 【发布时间】:2017-10-05 20:05:34 【问题描述】:在使用urllib.request.urlretrieve
时,我想知道是否有办法在控制台中查看打印的下载状态以及文件大小等信息?
这是我正在测试的代码:
#!/usr/bin/env python3.5.2
import urllib.request
import os
# make sure to change the directory before you test the code
directory = r'C:\Users\SalahGfx\Desktop\Downloads'
url = 'https://upload.wikimedia.org/wikipedia/en/d/d8/C4D_Logo.png'
def get_name_path():
image_name = url.split('/')[-1]
return os.path.join(directory, image_name)
urllib.request.urlretrieve(url, get_name_path())
print('The Image has been downloaded!')
【问题讨论】:
【参考方案1】:没有内置任何东西。您必须自己编写。幸运的是,这并不太难。您只需从标头中读取内容的长度,然后按块读取响应。这是代码
import urllib2, sys
def chunk_report(bytes_so_far, chunk_size, total_size):
percent = float(bytes_so_far) / total_size
percent = round(percent*100, 2)
sys.stdout.write("Downloaded %d of %d bytes (%0.2f%%)\r" %
(bytes_so_far, total_size, percent))
if bytes_so_far >= total_size:
sys.stdout.write('\n')
def chunk_read(response, chunk_size=8192, report_hook=None):
total_size = response.info().getheader('Content-Length').strip()
total_size = int(total_size)
bytes_so_far = 0
while 1:
chunk = response.read(chunk_size)
bytes_so_far += len(chunk)
if not chunk:
break
if report_hook:
report_hook(bytes_so_far, chunk_size, total_size)
return bytes_so_far
def get_name_path():
image_name = url.split('/')[-1]
return os.path.join(directory, image_name)
# make sure to change the directory before you test the code
directory = r'C:\Users\SalahGfx\Desktop\Downloads'
url = 'https://upload.wikimedia.org/wikipedia/en/d/d8/C4D_Logo.png'
response = urllib.request.urlopen(url, get_name_path())
chunk_read(response, report_hook=chunk_report)
请务必注意,我使用了urllib.request.urlopen
,因为urllib2.request.retrieve
被视为legacy,很快就会被弃用。
【讨论】:
谢谢你的好回答我现在明白了这样做背后的逻辑,但是我知道 urlopen 只接受没有文件名的 url 所以它是替换 urlretrieve 的唯一方法吗?以上是关于如何查看下载过程?的主要内容,如果未能解决你的问题,请参考以下文章