按CTRL + C退出以退出python程序

时间:2014-06-19 19:29:12

标签: python exit

尝试编写一个代码,该代码在代码中的任何位置按 CTRL + C 时出现问题,因为大多数在线帮助都是指信号和其他内容 这可能与要求的内容无关。可以跳过此部分并提供解决方案

import signal
import time

def sigint_handler(signum, frame):
    print 'Stop pressing the CTRL+C!'

signal.signal(signal.SIGINT, sigint_handler)

目标:

  

ctrl + c 应该退出程序

1 个答案:

答案 0 :(得分:4)

您可以在KeyboardInterrupt上尝试/除外:

try:
  while True:
    print 1
except KeyboardInterrupt:
  print "test"

或者,如果进程本身被终止,您将获得KILL命令发送的SIGTERM

如您所示,您可以定义处理程序:signal.signal(signal.SIGTERM, my_signal_term_handler)

以下是要考虑的所有UNIX信号的列表:http://en.wikipedia.org/wiki/Unix_signal#POSIX_signals。请注意,无法捕获SIGKILL。

相关问题