使用Tqdm在下载文件时添加进度条

4

我一直在尝试使用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并将括号留空时,进度条会按照应有的方式加载,但下载速度非常慢。
我在这里做错了什么?
2个回答

2

你的想法基本正确,但是缺少了使进度条正常工作所需的大部分代码。假设你已经创建了你的界面,在这里是我用于我的进度条的方法。它下载文件并将其保存在桌面上(但你可以指定你想要保存的位置)。它只是获取已下载文件的大小并除以总文件大小,然后使用该值来更新进度条。如果这段代码对你有帮助,请告诉我:

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

progress = 进度条


该标签用于创建进度条。

这个答案涉及到 chunk_sizeunit 之间的关系,我认为这并不太好。相反,我会创建一个 tqdm 对象,并在循环内使用 .update(len(chunk)) 。请参阅 https://github.com/tqdm/tqdm/blob/master/examples/tqdm_requests.py - Yuval

1
@Yuval的评论提升为答案以便于查看: 您可以像在tqdm请求包装器中一样调整您的tqdm对象。
progress_bar = tqdm(
    total=file_size,  # in bytes
    desc=f"Downloading {filename}",
    unit="B",
    unit_scale=True,
    unit_divisor=1024,  # make use of standard units e.g. KB, MB, etc.
    miniters=1,  # recommended for network progress that might vary strongly
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接