在 Python 中捕获 Control-C
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15318208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Capture Control-C in Python
提问by pauliwago
I want to know if it's possible to catch a Control-C in python in the following manner:
我想知道是否可以通过以下方式在 python 中捕获 Control-C:
if input != contr-c:
#DO THINGS
else:
#quit
I've read up on stuff with tryand except KeyboardInterruptbut they're not working for me.
我已经阅读了关于try和except KeyboardInterrupt但他们不适合我的东西。
采纳答案by pradyunsg
Consider reading thispage about handling exceptions.. It should help.
考虑阅读此页有关处理异常。应该帮助。
As @abarnerthas said, do sys.exit()after except KeyboardInterrupt:.
正如@abernert所说,sys.exit()在except KeyboardInterrupt:.
Something like
就像是
try:
# DO THINGS
except KeyboardInterrupt:
# quit
sys.exit()
You can also use the built in exit()function, but as @eryksunpointed out, sys.exitis more reliable.
您也可以使用内置exit()函数,但正如@eryksun指出的那样,sys.exit它更可靠。
回答by abarnert
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.
根据您的评论,听起来您唯一的问题except KeyboardInterrupt:是您不知道如何在遇到中断时使其退出。
If so, that's simple:
如果是这样,那很简单:
import sys
try:
user_input = input()
except KeyboardInterrupt:
sys.exit(0)

