Capture Control-C in Python

前端 未结 2 1484
我在风中等你
我在风中等你 2020-12-15 16:51

I want to know if it\'s possible to catch a Control-C in python in the following manner:

 if input != contr-c:
    #DO THINGS
 else:
    #quit
2条回答
  •  难免孤独
    2020-12-15 17:17

    Consider reading this page about handling exceptions.. It should help.

    As @abarnert has said, do sys.exit() after except KeyboardInterrupt:.

    Something like

    try:
        # DO THINGS
    except KeyboardInterrupt:
        # quit
        sys.exit()
    

    You can also use the built in exit() function, but as @eryksun pointed out, sys.exit is more reliable.

提交回复
热议问题