Save progress when Python exits abnormally?
黄舟
黄舟 2017-05-18 10:53:50
0
3
1054

Question:
Read text to generate a list. list.pop() while the program is running. Now I want to ask if I can rewrite the values ​​in the list into the text when exiting abnormally.
Exception:
Ctrl-c, kill, Ctrl-z
Thank you!

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
PHPzhong

The abnormal situations you mentioned are all caused by the program receiving the corresponding signal and taking the default action (exit), so you can use 注册信号, 改变默认动作 to avoid the program from exiting abnormally.

import signal
import time

def hander(signum, frame):
    # 接受到信号后你想做的事
    print signum, frame

signal.signal(signal.SIGTERM, hander)  # 捕获kill : SIGTERM信号
signal.signal(signal.SIGINT, hander)   # 捕获Ctrl-c: SIGTERM 信号(可以绑定不同的函数)
signal.signal(signal.SIGTSTP, hander)  # 捕获 Ctrl-z: SIGTSTP信号(可以绑定不同的函数)
while 1:
    time.sleep(1)

After the above signal将对应的信号动作绑定到hander函数, 在接受到Ctrl-c , kill , Ctrl-z都能分别执行handler的代码了, 至于想怎么实现, 可以自定义, 如果除了这些信号意外的情况, 得示其他情况而决定采取什么措施! 可以学习下python signalrelated knowledge (some signals cannot be captured, this is determined by the system, you need to pay attention)

左手右手慢动作

You can try to catch the exception in if main:

if __name__ == '__main__':
    try:
       main()
    except e:
       solve()
刘奇

There is a function in Python called atexit, which will call back when the program exits. General exits can be captured.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!