How do I capture SIGINT in Python?

前端 未结 12 1487
长发绾君心
长发绾君心 2020-11-21 22:54

I\'m working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a Ctrl+C sign

12条回答
  •  囚心锁ツ
    2020-11-21 23:32

    If you want to ensure that your cleanup process finishes I would add on to Matt J's answer by using a SIG_IGN so that further SIGINT are ignored which will prevent your cleanup from being interrupted.

    import signal
    import sys
    
    def signal_handler(signum, frame):
        signal.signal(signum, signal.SIG_IGN) # ignore additional signals
        cleanup() # give your process a chance to clean up
        sys.exit(0)
    
    signal.signal(signal.SIGINT, signal_handler) # register the signal with the signal handler first
    do_stuff()
    

提交回复
热议问题