Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is possible but you need to do a few things:</p> <ul> <li>Fake out the urllib2 subsystem into passing a file handle down to httplib by attaching a <code>__len__</code> attribute which makes <code>len(data)</code> return the correct size, used to populate the Content-Length header.</li> <li>Override the <code>read()</code> method on your file handle: as httplib calls <code>read()</code> your callback will be invoked, letting you calculate the percentage and update your progress bar.</li> </ul> <p>This could work with any file-like object, but I've wrapped <code>file</code> to show how it could work with a really large file streamed from disk:</p> <pre><code>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) </code></pre> <p>Output:</p> <pre><code>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 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload