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

Python多进程中KeyboardInterrupt无法优雅终止的问题求助

问题原因分析
  • 按下Ctrl+C时,系统会向Python进程发送SIGINT信号,Python默认会把这个信号转化为KeyboardInterrupt异常抛出。
  • 即便你注册了信号处理函数(比如你的shutdown函数),信号处理完成后,Python的主执行流程会回到中断前的位置,继续抛出KeyboardInterrupt,从而产生回溯信息。
  • 单进程场景下问题依然存在,是因为这是Python处理SIGINT的默认机制,和进程数量无关。
解决方法

捕获KeyboardInterrupt异常

在主程序入口用try-except块捕获该异常,阻止回溯输出:

import signal
import time

def shutdown(signum, frame):
    print("执行关闭操作...")
    # 添加上你的资源清理逻辑

signal.signal(signal.SIGINT, shutdown)

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    pass  # 直接跳过,避免回溯

在信号处理函数中直接终止进程

使用os._exit()替代常规退出方式,这样信号处理后不会回到主执行流,也就不会触发异常:

import signal
import time
import os

def shutdown(signum, frame):
    print("执行关闭操作...")
    # 执行资源清理
    os._exit(0)  # 直接终止进程,无后续异常抛出

signal.signal(signal.SIGINT, shutdown)

while True:
    time.sleep(1)

忽略SIGINT信号(仅适用于无需清理的场景)

如果不需要执行shutdown清理逻辑,可以直接忽略信号:

import signal
import time

signal.signal(signal.SIGINT, signal.SIG_IGN)

while True:
    time.sleep(1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:32:39