Skip to main content
 首页 » 编程设计

python之如何获取 urllib2 的上传进度条

2024年08月12日35小虾米

我目前使用以下代码将一个文件上传到远程服务器:

import MultipartPostHandler, urllib2, sys 
cookies = cookielib.CookieJar() 
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler) 
params = {"data" : open("foo.bar") } 
request=opener.open("http://127.0.0.1/api.php", params) 
response = request.read() 

这工作正常,但对于较大的文件,上传需要一些时间,如果有一个允许我显示上传进度的回调会很好吗?

我已经尝试过 kodakloader 解决方案,但它没有针对单个文件的回调。

有人知道解决方案吗?

请您参考如下方法:

这是我们的 python 依赖脚本的片段 Chris Phillips我在@ Cogi 工作过(尽管他做了这一部分)。完整的脚本是 here .

    try: 
        tmpfilehandle, tmpfilename = tempfile.mkstemp() 
        with os.fdopen(tmpfilehandle, 'w+b') as tmpfile: 
            print '  Downloading from %s' % self.alternateUrl 
 
            self.progressLine = '' 
            def showProgress(bytesSoFar, totalBytes): 
                if self.progressLine: 
                    sys.stdout.write('\b' * len(self.progressLine)) 
 
                self.progressLine = '    %s/%s (%0.2f%%)' % (bytesSoFar, totalBytes, float(bytesSoFar) / totalBytes * 100) 
                sys.stdout.write(self.progressLine) 
 
            urlfile = urllib2.urlopen(self.alternateUrl) 
            totalBytes = int(urlfile.info().getheader('Content-Length').strip()) 
            bytesSoFar = 0 
 
            showProgress(bytesSoFar, totalBytes) 
 
            while True: 
                readBytes = urlfile.read(1024 * 100) 
                bytesSoFar += len(readBytes) 
 
                if not readBytes: 
                    break 
 
                tmpfile.write(readBytes) 
                showProgress(bytesSoFar, totalBytes) 
 
    except HTTPError, e: 
        sys.stderr.write('Unable to fetch URL: %s\n' % self.alternateUrl) 
        raise