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

如何使键盘中断生效以终止Python线程?

如何让键盘中断停止Python线程?

问题原因

Python中,Ctrl+C触发的SIGINT信号只会发送给主线程。你之前的代码里,主线程启动子线程后就直接退出了,此时子线程仍在运行,但信号无法被已退出的主线程处理,导致信号处理函数从未被调用,程序无法终止。

解决方案

方案1:让主线程等待子线程(推荐)

修改代码让主线程保持活跃,通过join()等待子线程结束,这样主线程能接收SIGINT信号,触发处理函数控制子线程退出:

import signal
import threading
import time

runnable = True

def listen_thread():
    print("listen_thread starting", flush=True)
    while runnable:
        print(time.asctime(), flush=True)
        time.sleep(3)
    print("listen_thread stopping", flush=True)

def signal_handler(signal, frame):
    global runnable
    print("setting runnable to False", flush=True)
    runnable = False

if __name__ == '__main__':
    signal.signal(signal.SIGINT, signal_handler)
    thread = threading.Thread(target=listen_thread)
    thread.start()
    # 主线程等待子线程完成
    thread.join()

方案2:使用守护线程快速终止

如果不需要子线程执行清理操作,可以将子线程设为守护线程,主线程退出时会强制终止子线程:

import threading
import time

def listen_thread():
    print("listen_thread", flush=True)
    while True:
        print(time.asctime(), flush=True)
        time.sleep(3)

if __name__ == '__main__':
    thread = threading.Thread(target=listen_thread, daemon=True)
    thread.start()
    # 主线程保持活跃等待中断
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("程序终止")

方案3:用threading.Event实现线程安全的退出控制

使用Event代替全局变量,不仅线程安全,还能让中断响应更及时(wait()会在事件触发时立即返回,无需等待sleep结束):

import signal
import threading
import time

stop_event = threading.Event()

def listen_thread():
    print("listen_thread starting", flush=True)
    while not stop_event.is_set():
        print(time.asctime(), flush=True)
        # 用wait替代sleep,支持中断唤醒
        stop_event.wait(3)
    print("listen_thread stopping", flush=True)

def signal_handler(signal, frame):
    print("触发中断,停止线程", flush=True)
    stop_event.set()

if __name__ == '__main__':
    signal.signal(signal.SIGINT, signal_handler)
    thread = threading.Thread(target=listen_thread)
    thread.start()
    thread.join()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:55:27