本文介绍了在SIGINT之后保存工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序需要很长时间才能完成.我想要它可以捕获SIGINT(ctrl-c)并调用self.save_work()方法.

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.

按现状,我的signal_hander()无效,因为程序到达signal_handler()的时间未定义self.

As it stands, my signal_hander() does not work since self is not defined by the time the program reaches signal_handler().

如何设置它,以便在SIGINT之后调用self.save_work?

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()

推荐答案

如果只想捕获ctr + c,则可以捕获 KeyboardInterrupt 例外:

If you just want to catch ctr+c then you can catch the KeyboardInterrupt exception:

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()

并不是说我认为这毕竟是一个很好的设计.看来您需要使用函数而不是构造函数.

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.

这篇关于在SIGINT之后保存工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 04:34