我有一个需要很长时间才能完成的程序。我想要
它能够捕获SIGINT
(ctrl-c)并调用self.save_work()
方法。
目前,我的signal_hander()
无效
程序到达self
时未定义signal_handler()
。
如何进行设置,以便在self.save_work
之后调用SIGINT
?
#!/usr/bin/env python
import signal
def signal_handler(signal, frame):
self.save_work() # Does not work
exit(1)
signal.signal(signal.SIGINT, signal_handler)
class Main(object):
def do_stuff(self):
...
def save_work(self):
...
def __init__(self):
self.do_stuff()
self.save_work()
if __name__=='__main__':
Main()
答案 0 :(得分:4)
如果您只想捕获ctr + c,那么您可以捕获KeyboardInterrupt异常:
class Main(object):
def do_stuff(self):
...
def save_work(self):
...
def __init__(self):
try:
self.do_stuff()
except KeyboardInterrupt:
pass # Or print helpful info
self.save_work()
并不是说我认为这毕竟是一个很好的设计。看起来你需要使用函数而不是构造函数。
答案 1 :(得分:3)
通常,“工作”涉及某种大循环。要驯服你的循环,并防止它在未知步骤中破坏,你可以使用以下上下文管理器:
import signal
class GracefulInterruptHandler(object):
def __init__(self, sig=signal.SIGINT):
self.sig = sig
def __enter__(self):
self.interrupted = False
self.released = False
self.original_handler = signal.getsignal(self.sig)
def handler(signum, frame):
self.release()
self.interrupted = True
signal.signal(self.sig, handler)
return self
def __exit__(self, type, value, tb):
self.release()
def release(self):
if self.released:
return False
signal.signal(self.sig, self.original_handler)
self.released = True
return True
使用:
import time
/// do stuff:
with GracefulInterruptHandler() as h:
for i in xrange(1000):
print "..."
time.sleep(1)
if h.interrupted:
print "interrupted!"
time.sleep(5)
break
save_work()
答案 2 :(得分:2)
import signal
def signal_handler(signal, frame):
#do some stuff
def main():
#do some more stuff
if __name__=='__main__':
signal.signal(signal.SIGINT, signal_handler)
main()