Ctrl当你点击+时,有没有办法阻止回溯出现c,即KeyboardInterrupt
在 Python 脚本中引发?
问问题
14721 次
8 回答
41
试试这个:
import signal
import sys
signal.signal(signal.SIGINT, lambda x, y: sys.exit(0))
这样您就不需要将所有内容都包装在异常处理程序中。
于 2012-08-01T15:32:49.003 回答
7
try:
# do something
except KeyboardInterrupt:
pass
于 2011-08-16T03:19:00.383 回答
2
用 try/except 块捕捉它:
while True:
try:
print "This will go on forever"
except KeyboardInterrupt:
pass
于 2011-08-16T03:19:02.920 回答
2
try:
your_stuff()
except KeyboardInterrupt:
print("no traceback")
于 2011-08-16T03:19:26.253 回答
1
另请注意,默认情况下,解释器以状态码 128 + 您平台上的 SIGINT 值(在大多数系统上为 2)退出。
import sys, signal
try:
# code...
except KeyboardInterrupt: # Suppress tracebacks on SIGINT
sys.exit(128 + signal.SIGINT) # http://tldp.org/LDP/abs/html/exitcodes.html
于 2011-11-13T01:17:38.780 回答
0
使用上下文管理器抑制异常:
from contextlib import suppress
def output_forever():
while True:
print('endless script output. Press ctrl + C to exit')
if __name__ == '__main__':
with suppress(KeyboardInterrupt):
output_forever()
于 2022-02-13T09:34:48.553 回答
-5
import sys
try:
print("HELLO")
english = input("Enter your main launguage: ")
print("GOODBYE")
except KeyboardInterrupt:
print("GET LOST")
于 2015-06-30T08:04:37.567 回答