How do I capture SIGINT in Python?

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

    Register your handler with signal.signal like this:

    #!/usr/bin/env python
    import signal
    import sys
    
    def signal_handler(sig, frame):
        print('You pressed Ctrl+C!')
        sys.exit(0)
    signal.signal(signal.SIGINT, signal_handler)
    print('Press Ctrl+C')
    signal.pause()
    

    Code adapted from here.

    More documentation on signal can be found here.  

提交回复
热议问题