如何重载键盘中断?(Python)

11 投票
3 回答
13912 浏览
提问于 2025-04-16 23:10

有没有办法让我在脚本运行时,当按下Ctrl+c时,执行我的某个函数呢?

3 个回答

3

使用 KeyboardInterrupt 异常,然后在 except 块中调用你的函数。

9

当然可以。

try:
  # Your normal block of code
except KeyboardInterrupt:
  # Your code which is executed when CTRL+C is pressed.
finally:
  # Your code which is always executed.
23

看看这个关于 信号处理器 的内容。按下 CTRL-C 这个操作对应的是 SIGINT(在 POSIX 系统中是信号 #2)。

举个例子:

#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
    print("You pressed Ctrl+C - or killed me with -2")
    sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print("Press Ctrl+C")
signal.pause()

撰写回答