可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I need to download a sizable (~200MB) file. I figured out how to download and save the file with here. It would be nice to have a progress bar to know how much has been downloaded. I found ProgressBar but I'm not sure how to incorperate the two together.
Here's the code I tried, but it didn't work.
bar = progressbar.ProgressBar(max_value=progressbar.UnknownLength) with closing(download_file()) as r: for i in range(20): bar.update(i)
回答1:
I suggest you try tqdm
[1], it's very easy to use. Example code for downloading with requests
library[2]:
from tqdm import tqdm import requests import math url = "http://example.com/bigfile.bin" # 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 wrote = 0 with open('output.bin', 'wb') as f: for data in tqdm(r.iter_content(block_size), total=math.ceil(total_size//block_size) , unit='KB', unit_scale=True): wrote = wrote + len(data) f.write(data) if total_size != 0 and wrote != total_size: print("ERROR, something went wrong")
[1]: https://github.com/tqdm/tqdm
[2]: http://docs.python-requests.org/en/master/
回答2:
It seems that there is a disconnect between the examples on the Progress Bar Usage page and what the code actually requires.
In the following example, not the use of maxval
instead of max_value
. Also note the use of .start()
to initialized the bar. This has been noted in an 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)
回答3:
It seems like you're going to need to get the remote file size (answered here) to calculate how far along you are.
You could then update your progress bar while processing each chunk... if you know the total size and the size of the chunk, you can figure out when to update the progress bar.