无法在Windows上使用键盘Ctrl+C中断线程化Python控制台应用程序

2024-09-30 14:39:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法在Windows上使用Ctrl+C中断我的线程化Python产品应用程序,它继续运行,尝试了异常和信号处理。这是一个非常简化的代码版本,不会中断。单线程应用程序终止良好,与多线程Linux版本相同。有人能帮忙解决这个问题吗?提前谢谢。在

import threading
import time

class FooThread(threading.Thread):
    stop_flag = False

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        while not self.stop_flag:
            print(1)
            time.sleep(1)

t = FooThread()
t.start()

try:
    t.join()
except KeyboardInterrupt:
    t.stop_flag = True
    t.join()

Tags: importself版本应用程序timeinitwindowsdef
1条回答
网友
1楼 · 发布于 2024-09-30 14:39:12

你让你的线程成为一个守护进程,但你也需要保持你的“主”线程活着,以监听信号或键盘中断

带有信号的简单工作实现:

import threading
import time
import sys
import signal

class FooThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        while not self.stop_flag:
            print(1)
            time.sleep(1)

    stop_flag = False

def main():
    t = FooThread()
    def signal_handler(signal, frame):
        print('You pressed Ctrl+C!')
        t.stop_flag = True
        t.join()

    signal.signal(signal.SIGINT, signal_handler)
    t.start()

    while not t.stop_flag:
        time.sleep(1)

if __name__ == "__main__":
    main()

相关问题 更多 >