用Python捕获Control-C

pau*_*ago 29 python error-handling keyboard-events

我想知道是否可以通过以下方式在python中捕获Control-C:

 if input != contr-c:
    #DO THINGS
 else:
    #quit
Run Code Online (Sandbox Code Playgroud)

我已经阅读了有关的内容,但他们tryexcept KeyboardInterrupt没有为我工作.

pra*_*nsg 47

考虑阅读关于处理异常的这个页面.它应该有所帮助.

正如@abarnert所说,做完sys.exit()之后except KeyboardInterrupt:.

就像是

try:
    # DO THINGS
except KeyboardInterrupt:
    # quit
    sys.exit()
Run Code Online (Sandbox Code Playgroud)

您也可以使用内置exit()函数,但正如@eryksun指出的那样,sys.exit更可靠.


aba*_*ert 11

从你的评论中,听起来你唯一的问题except KeyboardInterrupt:就是当你得到那个中断时你不知道怎么让它退出.

如果是这样,那很简单:

import sys

try:
    user_input = input()
except KeyboardInterrupt:
    sys.exit(0)
Run Code Online (Sandbox Code Playgroud)