use*_*335 5 python download tqdm
我一直在尝试使用 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)
Run Code Online (Sandbox Code Playgroud)
问题是,当我chunk_size = 512在r.iter_content进度栏中插入时,在显示下载数据时根本不会加载,但是当我chunk_size = 512完全删除并将括号留空时,进度条会完全按照应有的方式加载,但下载速度很糟糕。
我在这里做错了什么?
您离目标并不远,但只是缺少几乎所有使进度条相应工作的代码。假设您已经创建了界面,这是我用于进度条的方法。它会下载文件并将其保存在桌面上(但您可以指定要保存的位置)。它只是获取下载的文件量并将其除以总文件大小,然后使用该值来更新进度条。让我知道这段代码是否有帮助:
url = 'http://alpha.chem.umb.edu/chemistry/ch115/Mridula/CHEM%20116/documents/chapter_20au.pdf'
save = 'C:/Users/' + username + "/Desktop/"
r = requests.get(url, stream=True)
total_size = int(r.headers["Content-Length"])
downloaded = 0 # keep track of size downloaded so far
chunkSize = 1024
bars = int(total_size / chunkSize)
print(dict(num_bars=bars))
with open(filename, "wb") as f:
for chunk in tqdm(r.iter_content(chunk_size=chunkSize), total=bars, unit="KB",
desc=filename, leave=True):
f.write(chunk)
downloaded += chunkSize # increment the downloaded
prog = ((downloaded * 100 / total_size))
progress["value"] = (prog) # *100 #Default max value of tkinter progress is 100
return
Run Code Online (Sandbox Code Playgroud)
progress= 进度条
| 归档时间: |
|
| 查看次数: |
6142 次 |
| 最近记录: |