Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- import time # for example
- from typing import Optional, Callable
- def keyboard_interrupt_handler(*, save: Optional[Callable],
- abort: Optional[Callable]) -> Callable:
- """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()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement