How do I capture SIGINT in Python?

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

    You can treat it like an exception (KeyboardInterrupt), like any other. Make a new file and run it from your shell with the following contents to see what I mean:

    import time, sys
    
    x = 1
    while True:
        try:
            print x
            time.sleep(.3)
            x += 1
        except KeyboardInterrupt:
            print "Bye"
            sys.exit()
    

提交回复
热议问题