Listing 2680
Submitted by rudsonalves, 8 February 2010
import os import sys import urllib import time # Characters ESC=chr(27) # download a file def download(url, style = 'quiet'): try: wget = urllib.urlopen(url) except IOError: raise IOError, '%s not found...' % url ESC = chr(27) # error mensage and error status. error_msg is 0 to download ok error_msg = '' status = 0 size = wget.info()['Content-Length'] if size.isdigit(): size = int(size) else: size = 0 fout = file(os.path.basename(url), 'w') total = 0 start_time = time.time() frist = True try: for line in wget: total += len(line) fout.write(line) if style == 'bar': curr_time = time.time() if size != 0: per = (100*total)/size speed = float(total)/(curr_time - start_time) remain = (size - total)/speed else: per = 100 speed = 0 remain = 0 bar = '#'*int(per*.60) + '>' + ' '*60 str_out = '[' + bar[:60] + '] %s ' % human_bytes(total) if not frist: sys.stdout.write(ESC + '[2A') else: print 'Download: %s Size: %s ' % (os.path.basename(url), \ human_bytes(size)) frist = False print 'Speed: %s/s Remain: %s ' % (human_bytes(int(speed)), \ human_time(int(remain))) print str_out elif style == 'quiet': pass else: print 'Donwload %s of %s' % (human_bytes(total), human_bytes(size)) except Exception, error_msg: # status is 1 for any error. error_msg return de python error message status = 1 if size != 0 and size != total: status = 1 error_msg = 'Size of the downloaded file does not match the source' fout.close() return status, error_msg

