Last active
August 30, 2016 07:46
-
-
Save brokkr/b399092b8153248a13f3a354dcbae73a to your computer and use it in GitHub Desktop.
Download a file with timeouts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib.request | |
import urllib.error | |
import signal | |
class NoMoreBufferException(Exception): | |
pass | |
class TimesUpException(Exception): | |
pass | |
def handler(signum, frame): | |
raise TimesUpException("Download timed out") | |
def download_block(u, f, block_size): | |
buffer = u.read(block_size) | |
if not buffer: | |
raise NoMoreBufferException("No more to download") | |
f.write(buffer) | |
def download_file(abspath, url): | |
'''Download function with block time outs''' | |
try: | |
u = urllib.request.urlopen(url) | |
except urllib.error.HTTPError as e: | |
return False | |
except: | |
return False | |
signal.signal(signal.SIGALRM, handler) | |
f = open(abspath, "wb") | |
block_size = 8192 | |
while True: | |
signal.alarm(60) | |
try: | |
download_block(u, f, block_size) | |
except NoMoreBufferException as e: | |
outcome = True | |
f.close() | |
break | |
except TimesUpException as e: | |
outcome = False | |
f.close() | |
delete_file(abspath) | |
break | |
signal.alarm(0) | |
signal.signal(signal.SIGALRM, signal.SIG_DFL) | |
return outcome |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment