Welcome Anonymous

What would you like to do?


Paste code remember you name for one cookie

Pasted by rudsonalves

Description função para download de arquivos da rede

On Monday 08 Feb 08:54

Language Python

Url http://paste.ideaslabs.com/show/LlULgJHVvQ

Download Here

  1. import os
  2. import sys
  3. import urllib
  4. import time
  5.  
  6. # Characters
  7. ESC=chr(27)
  8.  
  9. # download a file
  10. def download(url, style = 'quiet'):
  11.     try:
  12.         wget = urllib.urlopen(url)
  13.     except IOError:
  14.         raise IOError, '%s not found...' % url
  15.  
  16.     ESC = chr(27)
  17.  
  18.     # error mensage and error status. error_msg is 0 to download ok
  19.     error_msg = ''
  20.     status = 0
  21.  
  22.     size =  wget.info()['Content-Length']
  23.     if size.isdigit():
  24.         size = int(size)
  25.     else:
  26.         size = 0
  27.  
  28.     fout = file(os.path.basename(url), 'w')
  29.  
  30.     total = 0
  31.     start_time = time.time()
  32.     frist = True
  33.  
  34.     try:
  35.         for line in wget:
  36.             total += len(line)
  37.             fout.write(line)
  38.  
  39.             if style == 'bar':
  40.                 curr_time = time.time()
  41.                 if size != 0:
  42.                     per = (100*total)/size
  43.                     speed = float(total)/(curr_time - start_time)
  44.                     remain = (size - total)/speed
  45.                 else:
  46.                     per = 100
  47.                     speed = 0
  48.                     remain = 0
  49.                 bar = '#'*int(per*.60) + '>' + ' '*60
  50.                 str_out = '[' + bar[:60] + '] %s    ' % human_bytes(total)
  51.                 if not frist:
  52.                     sys.stdout.write(ESC + '[2A')
  53.                 else:
  54.                     print 'Download: %s     Size: %s    ' % (os.path.basename(url), \
  55.                                                             human_bytes(size))
  56.                     frist = False
  57.  
  58.                 print 'Speed: %s/s        Remain: %s    ' % (human_bytes(int(speed)), \
  59.                                                         human_time(int(remain)))
  60.                 print str_out
  61.             elif style == 'quiet':
  62.                 pass
  63.             else:
  64.                 print 'Donwload %s of %s' % (human_bytes(total), human_bytes(size))
  65.  
  66.     except Exception, error_msg:
  67.         # status is 1 for any error. error_msg return de python error message
  68.         status = 1
  69.  
  70.     if size != 0 and size != total:
  71.         status = 1
  72.         error_msg = 'Size of the downloaded file does not match the source'
  73.  
  74.     fout.close()
  75.  
  76.     return status, error_msg