Created
July 9, 2014 09:18
-
-
Save jhedev/84b9d56607110043ebee to your computer and use it in GitHub Desktop.
Decorator to add a KeyboardInterrupt handler to a function
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
#!/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