daily pastebin goal
24%
SHARE
TWEET

Untitled

a guest Feb 22nd, 2019 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import sys
  2. import time  # for example
  3. from typing import Optional, Callable
  4.  
  5. def keyboard_interrupt_handler(*, save: Optional[Callable],
  6.                                abort: Optional[Callable]) -> Callable:
  7.     """Use as decorator to handle KeyboardInterrupts while running a simulation.
  8.  
  9.     The given function objects for save and abort will be called depending on
  10.     the choice of aborting the simulation directly or saving the contents first.
  11.     """
  12.     def wrap(func):
  13.         def wrapped_func(*args, **kwargs):
  14.             try:
  15.                 func(*args, **kwargs)  # e.g. the simulation main function
  16.             except KeyboardInterrupt:
  17.                 store = None
  18.                 # ignoring everything else than y,n and emptystring
  19.                 while((store != "y") and (store != "n")):
  20.                     store = input("Aborting... store simulation data? (y/N): ")
  21.                     store = store.lower()  # not case sensitive
  22.                     if store == "":
  23.                         store = "n"
  24.  
  25.                 if store == "n":
  26.                     print("Aborting simulation...")
  27.                     if abort is not None:
  28.                         abort()
  29.                     sys.exit()
  30.  
  31.                 else:
  32.                     print("Storing simulation data...")
  33.                     if save is not None:
  34.                         save()
  35.                     sys.exit()
  36.  
  37.         return wrapped_func
  38.     return wrap
  39.    
  40.    
  41. # example ---------------------------------------------------------------------
  42. def savefunc():
  43.     print('hurrdurr, saving stuff')
  44.  
  45.  
  46. def abortfunc():
  47.     print('hurrdurr, aborting stuff')
  48.  
  49.  
  50. @keyboard_interrupt_handler(save=savefunc, abort=abortfunc)
  51. def testfunc():
  52.     for i in range(10):
  53.         print(i)
  54.         time.sleep(2)  # just there to give you enough time to find the keys ;)
  55.  
  56.  
  57. testfunc()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top