HolyMackerel! Usa gli strumenti!
import urllib2, sys, socket, time, os
def url_tester(url = "http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz"):
file_name = url.split('/')[-1]
u = urllib2.urlopen(url,None,1) # Note the timeout to urllib2...
file_size = int(u.info().getheaders("Content-Length")[0])
print ("\nDownloading: {} Bytes: {:,}".format(file_name, file_size))
with open(file_name, 'wb') as f:
file_size_dl = 0
block_sz = 1024*4
time_outs=0
while True:
try:
buffer = u.read(block_sz)
except socket.timeout:
if time_outs > 3: # file has not had activity in max seconds...
print "\n\n\nsorry -- try back later"
os.unlink(file_name)
raise
else: # start counting time outs...
print "\nHmmm... little issue... I'll wait a couple of seconds"
time.sleep(3)
time_outs+=1
continue
if not buffer: # end of the download
sys.stdout.write('\rDone!'+' '*len(status)+'\n\n')
sys.stdout.flush()
break
file_size_dl += len(buffer)
f.write(buffer)
status = '{:20,} Bytes [{:.2%}] received'.format(file_size_dl,
file_size_dl * 1.0/file_size)
sys.stdout.write('\r'+status)
sys.stdout.flush()
return file_name
Stampa uno stato come previsto. Se si scollega il mio cavo ethernet, ottengo:
Downloading: Python-2.7.3.tgz Bytes: 14,135,620
827,392 Bytes [5.85%] received
sorry -- try back later
Se si scollega il cavo, poi ricollegarlo in meno di 12 secondi, ottengo:
Downloading: Python-2.7.3.tgz Bytes: 14,135,620
716,800 Bytes [5.07%] received
Hmmm... little issue... I'll wait a couple of seconds
Hmmm... little issue... I'll wait a couple of seconds
Done!
Il file viene scaricato correttamente.
È possibile vedere che urllib2 supporta entrambi i timeout e riconnette. Se si disconnette e si rimane disconnessi per 3 * 4 secondi == 12 secondi, si interromperà per sempre e si genererà un'eccezione irreversibile. Questo potrebbe essere affrontato pure.
È possibile generare un'eccezione nel reportage. – Tobold
Sì, sollevare un'eccezione sembra essere il modo popolare per interrompere il download, da una rapida occhiata a Google. Tuttavia non è menzionato nella documentazione, il che mi fa temere che potrebbe avere un comportamento inaspettato. Ad esempio, forse i dati vengono recuperati da un thread dedicato e il lancio di un'eccezione lo renderà orfano e in realtà non interromperà il download. – Kevin