public
Created

Handle Keyboard Interrupt for critical functions

  • Download Gist
safe_keyboardinterrupt.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
#!/usr/bin/env python3
 
"""See the docstring of SafeInterruptHandler.
Works with python3 as well.
"""
 
__author__ = 'Arpad Horvath'
 
import signal
import functools
try:
import urllib.request
except ImportError:
import urllib
import os
import sys
 
def decorator(d):
"Make function d a decorator: d wraps a function fn. @author Darius Bacon"
return lambda fn: functools.update_wrapper(d(fn), fn)
decorator = decorator(decorator)
 
class SafeInterruptHandler(object):
"""Handle interrupt in critical cases.
 
SafeInterruptHandler.on()
and
SafeInterruptHandler.off()
you can switch on and off the special working.
 
You can create a safe function with the
@SafeInterruptHandler.decorator
decorator.
"""
finish = False
 
@classmethod
def signal_handler(cls, signal, frame):
cls.finish = True
 
@classmethod
def on(cls):
signal.signal(signal.SIGINT, cls.signal_handler)
 
@classmethod
def off(cls):
signal.signal(signal.SIGINT, signal.default_int_handler)
 
@classmethod
def decorator(cls, fn):
def fn_(*args, **kwargs):
cls.on()
fn(*args, **kwargs)
cls.off()
if cls.finish:
sys.exit(1)
return fn_
 
 
urlretrieve = urllib.urlretrieve if "urlretrieve" in dir(urllib) else urllib.request.urlretrieve
 
@SafeInterruptHandler.decorator
def download_files(files, baseurl, path="."):
if not baseurl[-1] == "/":
baseurl += "/"
if isinstance(files, str):
files = [files]
for file_ in files:
urlretrieve("".join([baseurl, file_]),
os.path.join(path, file_))
 
def test():
while True:
print("S")
download_files("splash_eu.jpg", "http://bocs.eu")
 
if __name__ == "__main__":
test()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.