Capture Control-C in Python

2019-01-23 23:25发布

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

I've read up on stuff with try and except KeyboardInterrupt but they're not working for me.

2条回答
Ridiculous、
2楼-- · 2019-01-23 23:36

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.

查看更多
女痞
3楼-- · 2019-01-23 23:39

From your comments, it sounds like your only problem with except KeyboardInterrupt: is that you don't know how to make it exit when you get that interrupt.

If so, that's simple:

import sys

try:
    user_input = input()
except KeyboardInterrupt:
    sys.exit(0)
查看更多
登录 后发表回答