python - How to prompt a user if they are sure they want to exit the program on a KeyboardInterrupt? -
when hit ctrl-c prompt pops on screen , input no because want keep running program program exits anyway. going wrong? functionality possible?
from functools import wraps import sys class cleanexit(object): def __init__(self, *args, **kw): # can supply optional function # called when keyboardinterrupt # takes place. # if function doesn't require arguments: # @cleanexit(handler=func) # if function requires arguments: # @cleanexit('foo', handler=handle) self.kw = kw self.args = args self.handler = kw.get('handler') def __call__(self, original_func): decorator_self = self @wraps(original_func) def wrappee(*args, **kwargs): try: original_func(*args,**kwargs) except keyboardinterrupt: if self.handler: self.handler(*self.args) else: sys.exit(0) return wrappee def handle(): answer = raw_input("are sure want exit?").lower().strip() if 'y' in answer: sys.exit(0) @cleanexit(handler=handle) def f(): while 1: pass f()
your problem you're not doing continue function after handling - code handles interrupt, , exits anyway. can recursively re-enter wrappee if handler exits this:
def __call__(self, original_func): decorator_self = self @wraps(original_func) def wrappee(*args, **kwargs): try: original_func(*args,**kwargs) except keyboardinterrupt: if self.handler: self.handler(*self.args) wrappee(*args, **kwargs) else: sys.exit(0) return wrappee
now should work. note little bit naughty, python can't optimise tail calls, if keyboardinterrupt
more sys.getrecursionlimit()
, python run out of stack frames , crash.
edit: silly - having thought it, function trivial derecurse hand doesn't count.
def __call__(self, original_func): decorator_self = self @wraps(original_func) def wrappee(*args, **kwargs): while true: try: original_func(*args,**kwargs) except keyboardinterrupt: if self.handler: self.handler(*self.args) else: sys.exit(0) return wrappee
should work fine.
Comments
Post a Comment