Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Handle Keyboard Interrupt for critical functions
#!/usr/bin/env python3
"""See the docstring of SafeInterruptHandler.
Works with python3 as well.
__author__ = 'Arpad Horvath'
import signal
import functools
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.
you can switch on and off the special working.
You can create a safe function with the
finish = False
def signal_handler(cls, signal, frame):
cls.finish = True
def on(cls):
signal.signal(signal.SIGINT, cls.signal_handler)
def off(cls):
signal.signal(signal.SIGINT, signal.default_int_handler)
def decorator(cls, fn):
def fn_(*args, **kwargs):
fn(*args, **kwargs)
if cls.finish:
return fn_
urlretrieve = urllib.urlretrieve if "urlretrieve" in dir(urllib) else urllib.request.urlretrieve
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:
download_files("splash_eu.jpg", "")
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment