How do I capture SIGINT in Python?

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

    thanks for existing answers, but added signal.getsignal()

    import signal
    
    # store default handler of signal.SIGINT
    default_handler = signal.getsignal(signal.SIGINT)
    catch_count = 0
    
    def handler(signum, frame):
        global default_handler, catch_count
        catch_count += 1
        print ('wait:', catch_count)
        if catch_count > 3:
            # recover handler for signal.SIGINT
            signal.signal(signal.SIGINT, default_handler)
            print('expecting KeyboardInterrupt')
    
    signal.signal(signal.SIGINT, handler)
    print('Press Ctrl+c here')
    
    while True:
        pass
    

提交回复
热议问题