Using Tqdm to add a progress bar when downloading files

I am trying to tune a progress bar using the Tqdm module in python 3.6, but it seems I'm halfway there.

My code is as follows:

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)

The problem is that when I insert chunk_size = 512in r.iter_content, the progress bar does not load at all when showing the loaded data, but when I completely delete chunk_size = 512and leave the parentheses empty, the bar loads in the same way as it should, but the download speed is terrible.

What am I doing wrong here?

+4
source share
1 answer

, , . , , , . ( , ). , , . , :

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=

+1

Source: https://habr.com/ru/post/1676175/


All Articles