How to get an upload progress bar for urllib2?
I currently use the following code to upload one file to a remote server:
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()
This works fine, but for larger files the upload takes some time, and it would be nice to have a callback that allows me to display the upload progress?
I already tried the kodakloader solution, but it does not has a callback for a single file.
Does anyone knows 开发者_如何学Ca solution?
Here's a snippet from our python dependency script that Chris Phillips and I worked on @ Cogi (though he did this particular portion of it). Complete script is 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
I think it's impossible to know upload progress with urllib2. I'm looking into using pycurl.
精彩评论