当我按ctrl-c时,屏幕上会弹出提示,我输入no 因为我想继续运行程序,但程序还是退出了。 我哪里出错了?这个功能可能吗?你知道吗
from functools import wraps
import sys
class CleanExit(object):
def __init__(self, *args, **kw):
# You can supply an optional function
# to be called when the KeyboardInterrupt
# takes place.
# If the function doesn't require any arguments:
# @CleanExit(handler=func)
# If the 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 you sure you want to exit?").lower().strip()
if 'y' in answer:
sys.exit(0)
@CleanExit(handler=handle)
def f():
while 1: pass
f()
您的问题是,在处理完函数之后,您没有做任何事情来继续它—因此您的代码处理中断,然后无论如何都会退出。如果处理程序成功退出,则可以递归地重新输入wrappee,如下所示:
现在应该可以了。请注意,这有点顽皮,因为Python无法优化尾部调用,因此如果您
KeyboardInterrupt
的频率高于sys.getrecursionlimit()
,Python将耗尽堆栈帧并崩溃。你知道吗编辑:这是愚蠢的-已经想过了,这个功能是如此微不足道的解除诅咒的手,它可能甚至不计算。你知道吗
也应该很好。你知道吗
相关问题 更多 >
编程相关推荐