You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Python程序无KeyboardInterrupt代码仍可通过Ctrl+C中断?

问题:未处理KeyboardInterrupt却能中断MCP3008读取程序的原因?

我正在学习基础Python编程,在查看Adafruit的一段MCP3008模拟输入读取代码时产生疑问:代码中未包含KeyboardInterrupt相关处理逻辑,但按下Ctrl+C仍能中断程序。代码如下:

# Simple example of reading the MCP3008 analog input channels and printing
# them all out.
# Author: Tony DiCola
# License: Public Domain
import time

# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008


# Software SPI configuration:
# CLK  = 18
# MISO = 23
# MOSI = 24
# CS   = 25
# mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)

# Hardware SPI configuration:
SPI_PORT   = 0
SPI_DEVICE = 0
mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))


print('Reading MCP3008 values, press Ctrl-C to quit...')
# Print nice channel column headers.
print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*range(8)))
print('-' * 57)
# Main program loop.
while True:
    # Read all the ADC channel values in a list.
    values = [0]*8
    for i in range(8):
        # The read_adc function will get the value of the specified channel (0-7).
        values[i] = mcp.read_adc(i)
    # Print the ADC values.
    print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values))
    # Pause for half a second.
    time.sleep(0.5)

请问该中断功能是否由导入的Adafruit相关库实现?


回答

这不是Adafruit相关库实现的,而是Python本身的默认信号处理机制:

  • 按下Ctrl+C时,操作系统会向Python进程发送SIGINT中断信号。
  • Python默认会将这个信号转换为KeyboardInterrupt异常。
  • 如果代码没有显式用try-except块捕获这个异常,程序就会直接终止并打印异常调用栈——这就是你看到的中断效果。

代码里的while True循环、mcp.read_adc()调用或者time.sleep(),只要程序处于运行状态,收到SIGINT信号就会触发这个默认行为。Adafruit的库仅负责和MCP3008硬件通信,没有额外实现信号中断逻辑。


内容的提问来源于stack exchange,提问作者Smlekmew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:21:50