sam*_*ias 24
这是可能的,但你需要做一些事情:
__len__属性len(data),用于填充Content-Length标头.read()文件句柄上的方法:作为httplib read()调用,将调用您的回调,让您计算百分比并更新进度条.这可以适用于任何类似文件的对象,但我已经打包file以显示它如何与从磁盘流传输的非常大的文件一起工作:
import os, urllib2
from cStringIO import StringIO
class Progress(object):
def __init__(self):
self._seen = 0.0
def update(self, total, size, name):
self._seen += size
pct = (self._seen / total) * 100.0
print '%s progress: %.2f' % (name, pct)
class file_with_callback(file):
def __init__(self, path, mode, callback, *args):
file.__init__(self, path, mode)
self.seek(0, os.SEEK_END)
self._total = self.tell()
self.seek(0)
self._callback = callback
self._args = args
def __len__(self):
return self._total
def read(self, size):
data = file.read(self, size)
self._callback(self._total, len(data), *self._args)
return data
path = 'large_file.txt'
progress = Progress()
stream = file_with_callback(path, 'rb', progress.update, path)
req = urllib2.Request(url, stream)
res = urllib2.urlopen(req)
Run Code Online (Sandbox Code Playgroud)
输出:
large_file.txt progress: 0.68
large_file.txt progress: 1.36
large_file.txt progress: 2.04
large_file.txt progress: 2.72
large_file.txt progress: 3.40
...
large_file.txt progress: 99.20
large_file.txt progress: 99.87
large_file.txt progress: 100.00
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4603 次 |
| 最近记录: |