How do I capture SIGINT in Python?

前端 未结 12 1528
长发绾君心
长发绾君心 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:27

    In contrast to Matt J his answer, I use a simple object. This gives me the possibily to parse this handler to all the threads that needs to be stopped securlery.

    class SIGINT_handler():
        def __init__(self):
            self.SIGINT = False
    
        def signal_handler(self, signal, frame):
            print('You pressed Ctrl+C!')
            self.SIGINT = True
    
    
    handler = SIGINT_handler()
    signal.signal(signal.SIGINT, handler.signal_handler)
    

    Elsewhere

    while True:
        # task
        if handler.SIGINT:
            break
    

提交回复
热议问题