通过带有请求的http下载文件时的进度条

2024-05-06 17:47:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要下载一个很大的(~200MB)文件。我想出了如何用here下载和保存文件。如果有一个进度条可以知道下载了多少,那就太好了。我找到了ProgressBar,但我不知道如何将两者结合起来。

这是我试过的代码,但没用。

bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength)
with closing(download_file()) as r:
    for i in range(20):
        bar.update(i)

Tags: 文件代码进度条herevaluedownloadaswith
3条回答

我建议你试试tqdm[1],它很容易使用。 使用requests库[2]下载的示例代码:

from tqdm import tqdm
import requests

url = "http://www.ovh.net/files/10Mb.dat" #big file test
# Streaming, so we can iterate over the response.
r = requests.get(url, stream=True)
# Total size in bytes.
total_size = int(r.headers.get('content-length', 0))
block_size = 1024 #1 Kibibyte
t=tqdm(total=total_size, unit='iB', unit_scale=True)
with open('test.dat', 'wb') as f:
    for data in r.iter_content(block_size):
        t.update(len(data))
        f.write(data)
t.close()
if total_size != 0 and t.n != total_size:
    print("ERROR, something went wrong")

[1]:https://github.com/tqdm/tqdm
[2] :http://docs.python-requests.org/en/master/

似乎您需要获取远程文件大小(answered here)来计算您的进展情况。

然后,你可以在处理每个块时更新进度条。。。如果知道块的总大小和大小,就可以确定何时更新进度条。

似乎Progress Bar Usage页面上的示例与代码实际需要的内容之间存在脱节。

在下面的示例中,请注意使用maxval,而不是max_value。还要注意使用.start()初始化条。这已经在Issue中注意到了。

import progressbar
import requests

url = "http://stackoverflow.com/"


def download_file(url):
    local_filename = 'test.html'
    r = requests.get(url, stream=True)
    f = open(local_filename, 'wb')
    file_size = int(r.headers['Content-Length'])
    chunk = 1
    num_bars = file_size / chunk
    bar =  progressbar.ProgressBar(maxval=num_bars).start()
    i = 0
    for chunk in r.iter_content():
        f.write(chunk)
        bar.update(i)
        i+=1
    f.close()
    return

download_file(url)

相关问题 更多 >