2017-05-02 140 views
4

我一直在尝试在python 3.6中使用Tqdm模块设置进度条,但似乎我在这里一半。使用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) 

的问题是,当我插入chunk_size = 512r.iter_content同时显示下载数据的进度条不加载在所有的,但是当我完全删除chunk_size = 512和将圆括号留空即可,因为下载速度非常糟糕。

我在这里做错了什么?

回答

1

你并不遥远,只是简单地遗漏了所有的代码,使进度条相应地工作。假设你已经创建了你的界面,下面是我用于我的进度条的一种方法。它下载文件并将其保存在桌面上(但您可以指定要保存的位置)。它只需要下载多少文件并将其除以总文件大小,然后使用该值更新进度栏。让我知道如果这个代码可以帮助:

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(fileSize/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/fileSize)) 
     progress["value"] = (prog) # *100 #Default max value of tkinter progress is 100 

return 

progress =进度条