如何为urllib2获取上传进度条?

2 投票
2 回答
1726 浏览
提问于 2025-04-16 01:15

我现在用以下代码来上传一个文件到远程服务器:

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的解决方案,但它没有针对单个文件的回调。

有没有人知道有什么解决办法?

2 个回答

3

这是我们在Cogi公司一起工作的Python依赖脚本的一部分,作者是Chris Phillips和我(不过这部分是他做的)。完整的脚本可以在这里找到。

    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
1

我觉得用urllib2是无法知道上传进度的。我正在考虑使用pycurl。

撰写回答