python urllib2下载大小 [英] python urllib2 download size
本文介绍了python urllib2下载大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用urllib2下载一个文件,同时我想显示一个进度条..
但是如何获得实际下载的文件大小?
我当前的代码是
ul = urllib2.urlopen('www.file.com/blafoo.iso')
data = ul.get_data()
或
()$($)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ p>
如果从网站收到整个下载,则首先将数据写入该文件。
如何访问下载的数据大小?
感谢您的帮助
解决方案
以下是使用真棒请求的文本进度条的示例库和 progressbar 库:
导入请求
import progressbar
ISO =http://www.ubuntu.com/start-download?distro=桌面& bits = 32& release = lts
CHUNK_SIZE = 1024 * 1024#1MB
r = requests.get(ISO)
total_size = int(r.headers ['content -length'])
pbar = progressbar.ProgressBar(maxval = total_size).start()
file_contents =
用于r.iter_content中的块(chunk_size = CHUNK_SIZE) :
file_contents + = chunk
pbar.update(len(file_contents))
这是我在运行时在控制台中看到的:
$ python requests_progress.py
90%| ################## ########## |
编辑:一些注释:
- 并非所有服务器都提供内容长度标题,因此在这种情况下,您不能提供百分比
- 您可能不想要如果它是大的,读内存中的整个文件。您可以将这些块写入文件或其他地方。
iwant to download a file with the urllib2, and meanwhile i want to display a progress bar.. but how can i get the actual downloaded filesize?
my current code is
ul = urllib2.urlopen('www.file.com/blafoo.iso')
data = ul.get_data()
or
open('file.iso', 'w').write(ul.read())
The data is first written to the file, if the whole download is recieved from the website. how can i access the downloaded data size?
Thanks for your help
解决方案
Here's an example of a text progress bar using the awesome requests library and the progressbar library:
import requests
import progressbar
ISO = "http://www.ubuntu.com/start-download?distro=desktop&bits=32&release=lts"
CHUNK_SIZE = 1024 * 1024 # 1MB
r = requests.get(ISO)
total_size = int(r.headers['content-length'])
pbar = progressbar.ProgressBar(maxval=total_size).start()
file_contents = ""
for chunk in r.iter_content(chunk_size=CHUNK_SIZE):
file_contents += chunk
pbar.update(len(file_contents))
This is what I see in the console while running:
$ python requests_progress.py
90% |############################ |
Edit: some notes:
- Not all servers provide a content-length header, so in that case, you can't provide a percentage
- You might not want to read the whole file in memory if it's big. You can write the chunks to a file, or somewhere else.
这篇关于python urllib2下载大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文