search

Home  >  Q&A  >  body text

Save progress when Python exits abnormally?

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!

黄舟黄舟2780 days ago1133

reply all(3)I'll reply

  • PHPz

    PHPz2017-05-18 10:55:50

    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)

    reply
    0
  • ringa_lee

    ringa_lee2017-05-18 10:55:50

    You can try to catch the exception in if main:

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

    reply
    0
  • 怪我咯

    怪我咯2017-05-18 10:55:50

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

    reply
    0
  • Cancelreply