Python detect kill request

后端 未结 1 487
梦如初夏
梦如初夏 2021-01-21 03:46

I have a python 3 script and it runs on boot. And it work with some resources I want it free on exit.

How can I manage that script is going to exit if I\'m killing it wi

相关标签:
1条回答
  • 2021-01-21 03:55

    The signal module is what you are looking for.

    import signal
    
    def handler(signum, frame):
        print('Signal handler called with signal', signum)
    
    signal.signal(signal.SIGABRT, handler)
    

    Within the handler function you could terminate with sys.exit().

    However, it is more common to use SIGINT (that's what happens when you press CTRL+C in the terminal) or SIGTERM to terminate a program. If you don't have cleanup code you don't need to write a single line of code to handle SIGINT - by default it raises a KeyboardInterrupt exception which, if not caught (that's a reason why you should never use blank except: statements), causes your program to terminate.

    0 讨论(0)
提交回复
热议问题