SIGINT 后保存工作
我有一个需要很长时间才能完成的程序。我想 它能够捕获 SIGINT
(ctrl-c) 并调用 self.save_work()
方法。
就目前情况而言,我的 signal_hander()
无法正常工作 当程序到达 signal_handler()
时,self
尚未定义。
我如何设置它以便在 SIGINT
之后调用 self.save_work
?
#!/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()
I have a program which takes a long time to complete. I would like
it to be able to catch SIGINT
(ctrl-c) and call the self.save_work()
method.
As it stands, my signal_hander()
does not work sinceself
is not defined by the time the program reaches signal_handler()
.
How can I set it up so self.save_work
gets called after a 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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只想捕获 ctr+c 那么您可以捕获 KeyboardInterrupt 例外:
我并不认为这是一个好的设计。看来您需要使用函数而不是构造函数。
If you just want to catch ctr+c then you can catch the KeyboardInterrupt exception:
Not that I think this is a good design after all. It looks like you need to be using a function instead of a constructor.
通常,“工作”涉及某种大循环。要驯服循环并防止其在未知步骤中中断,您可以使用以下上下文管理器:
使用:
从此处: https://gist.github.com/2907502
Usually, "work" involves some kind of a big loop. To tame your loop, and prevent it from breaking in an unknown step, you can use the following context manager:
To use:
From here: https://gist.github.com/2907502