Last active
September 8, 2020 10:05
-
-
Save krauthex/52c5a6e0a77b5e3c421542214b096543 to your computer and use it in GitHub Desktop.
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 sys | |
import time # for example | |
from typing import Optional, Callable, Any | |
def keyboard_interrupt_handler(*, save: Optional[Callable[..., Any], | |
abort: Optional[Callable[..., Any]) -> Callable[..., Any]: | |
"""Use as decorator to handle KeyboardInterrupts while running a simulation. | |
The given function objects for save and abort will be called depending on | |
the choice of aborting the simulation directly or saving the contents first. | |
""" | |
def wrap(func): | |
def wrapped_func(*args, **kwargs): | |
try: | |
func(*args, **kwargs) # e.g. the simulation main function | |
except KeyboardInterrupt: | |
store = None | |
# ignoring everything else than y,n and emptystring | |
while((store != "y") and (store != "n")): | |
store = input("Aborting... store simulation data? (y/N): ") | |
store = store.lower() # not case sensitive | |
if store == "": | |
store = "n" | |
if store == "n": | |
print("Aborting simulation...") | |
if abort is not None: | |
abort() | |
sys.exit() | |
else: | |
print("Storing simulation data...") | |
if save is not None: | |
save() | |
sys.exit() | |
return wrapped_func | |
return wrap | |
# example --------------------------------------------------------------------- | |
def savefunc(): | |
print('hurrdurr, saving stuff') | |
def abortfunc(): | |
print('hurrdurr, aborting stuff') | |
@keyboard_interrupt_handler(save=savefunc, abort=abortfunc) | |
def testfunc(): | |
for i in range(10): | |
print(i) | |
time.sleep(2) # just there to give you enough time to find the keys ;) | |
testfunc() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment