2010-07-13 45 views
2

我目前使用下面的代码上传一个文件到远程服务器:如何获取urllib2的上传进度条?

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

有没有人知道解决方案?

回答

1

我认为用urllib2知道上传进度是不可能的。我正在研究使用pycurl。

+0

它看起来像这样解决了我的问题:http://pycurl.sourceforge.net/doc/callbacks.html – leoluk 2010-08-16 14:16:55

3

下面是我们的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 
+1

这显示下载的进度,是否正确?该问题要求进度条上传... – priestc 2010-07-20 07:24:39