40

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

 if input != contr-c:
    #DO THINGS
 else:
    #quit

我已经阅读了一些东西,tryexcept KeyboardInterrupt它们对我不起作用。

4

2 回答 2

66

考虑阅读有关处理异常的页面。它应该会有所帮助

正如@abarnert所说,sys.exit()except KeyboardInterrupt:.

就像是

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

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

于 2013-03-10T04:44:14.490 回答
15

从您的评论中,听起来您唯一的问题except KeyboardInterrupt:是当您收到中断时您不知道如何让它退出。

如果是这样,那很简单:

import sys

try:
    user_input = input()
except KeyboardInterrupt:
    sys.exit(0)
于 2013-03-10T02:39:06.897 回答