2017-05-02 139 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 =進度條