Advertisement
rfmonk

urllib_urlretrieve.py

Feb 10th, 2014
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # this is from The Python
  4. # Standard Library by example
  5. # ISBN13: 9780321767349
  6.  
  7. import urllib
  8. import os
  9.  
  10.  
  11. def reporthook(blocks_read, block_size, total_size):
  12.     """total_size is reported in bytes.
  13.    block_size is the amount read each time.
  14.    blocks_read is the number of blocks successfully read.
  15.    """
  16.  
  17.     if not blocks_read:
  18.         print 'Connection opened'
  19.         return
  20.     if total_size < 0:
  21.         # Unknown size
  22.         print 'Read %d blocks (%d bytes)' % (blocks_read, blocks_read *
  23.                                              block_size)
  24.     else:
  25.         amount_read = blocks_read * block_size
  26.         print 'Read %d blocks, or %d%d' % (blocks_read, amount_read,
  27.                                            total_size)
  28.         return
  29.  
  30. try:
  31.     filename, msg = urllib.urlretrieve(
  32.         'http://blog.doughellmann.com/', reporthook=reporthook)
  33.     print
  34.     print 'File:', filename
  35.     print 'Headers:'
  36.     print msg
  37.     print 'File exists before cleanup:', os.path.exists(filename)
  38.  
  39. finally:
  40.     urllib.urlcleanup()
  41.  
  42.     print 'File still exists:', os.path.exists(filename)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement