处理意外的关闭python

时间:2018-09-10 13:43:50

标签: python

有什么方法可以捕获python中程序意外关闭的异常吗?

让我说我正在控制台中运行python脚本,然后我不按 control + c 来停止程序,而是只需单击控制台的关闭按钮,便可以捕获任何内容控制台关闭前出现错误?

像这样:

try:
    print("hello")
except KeyboardInterrupt:
    exit()
except UnexpectedClose:
    print("unexpected shutoff")
    exit()

预先感谢

1 个答案:

答案 0 :(得分:0)

在我已经在上面的注释中加入link之后,阅读here,这表明强制关闭正在发送SIGHUP,此修改后的版本会在终端窗口关闭且python进程被“杀死”。

注意,我只是结合了SE上的可用信息(引用)。

import signal
import time

class GracefulKiller:
    kill_now = False
    def __init__(self):
        signal.signal(signal.SIGINT, self.exit_gracefully)
        signal.signal(signal.SIGTERM, self.exit_gracefully)
        signal.signal(signal.SIGHUP, self.exit_gracefully)

    def exit_gracefully(self,signum, frame):
        with open('kill.txt', 'w') as fpntr:
            fpntr.write('killed')
        self.kill_now = True

if __name__ == '__main__':
    killer = GracefulKiller()
    while True:
        time.sleep(1)
        print("doing something in a loop ...")
        if killer.kill_now:
            break
    print "End of the program. I was killed gracefully :)"