Skip to content

Instantly share code, notes, and snippets.

@jhedev
Created July 9, 2014 09:18
Show Gist options
  • Save jhedev/84b9d56607110043ebee to your computer and use it in GitHub Desktop.
Save jhedev/84b9d56607110043ebee to your computer and use it in GitHub Desktop.
Decorator to add a KeyboardInterrupt handler to a function
#!/usr/bin/env python3.3
# -*- coding: utf-8 -*-
import time
def interrupt_decorator(handler):
def decorator(fun):
def wrapper(*args, **kwargs):
try:
fun(*args, **kwargs)
except KeyboardInterrupt:
handler()
return wrapper
return decorator
def fun():
try:
print("running...")
time.sleep(30)
print("finished")
except KeyboardInterrupt:
print("exiting...")
@interrupt_decorator(lambda: print("exiting"))
def fun2():
print("running...")
time.sleep(30)
print("finished")
fun2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment