或者你可以想出一个替代方案来解决我的问题。基本上,我有一个类,里面有一堆函数,我想用try/except块来截获键盘中断(KeyboardInterrupt)错误,因为我有一个清理每个函数的函数。在
我想我可以创建一个decorator来代替在每个函数中放置巨大的try-catch块,但是我遇到了一些问题。到目前为止我有这样的东西class MyClass:
def catch_interrupt(self, func):
def catcher():
try:
func()
except KeyboardInterrupt:
self.End()
return catcher
@catch_interrupt
def my_func(self):
# Start a long process that might need to be interrupted
def End(self):
# Cleans up things
sys.exit()
当我运行这个时,问题是我得到了错误
^{pr2}$
这有可能吗?有没有更好的方法或者我真的应该把try/except块放在每个函数的内部?在