我一直在尝试使用Python 3.6中的Tqdm模块设置进度条,但似乎我只完成了一半。
我的代码如下:
from tqdm import tqdm
import requests
import time
url = 'http://alpha.chem.umb.edu/chemistry/ch115/Mridula/CHEM%20116/documents/chapter_20au.pdf'
# Streaming, so we can iterate over the response.
r = requests.get(url, stream=True)
#Using The Url as a filename
local_filename = url.split('/')[-1]
# Total size in bytes.
total_size = int(r.headers.get('content-length', 0))
#Printing Total size in Bytes
print(total_size)
#TQDM
with open(local_filename, 'wb') as f:
for data in tqdm(r.iter_content(chunk_size = 512), total=total_size, unit='B', unit_scale=True):
f.write(data)
问题在于,当我在
r.iter_content
中插入chunk_size = 512
时,进度条根本不加载,同时显示下载数据,但是当我完全删除chunk_size = 512
并将括号留空时,进度条会按照应有的方式加载,但下载速度非常慢。我在这里做错了什么?
chunk_size
和unit
之间的关系,我认为这并不太好。相反,我会创建一个tqdm
对象,并在循环内使用.update(len(chunk))
。请参阅 https://github.com/tqdm/tqdm/blob/master/examples/tqdm_requests.py - Yuval