首页 > 解决方案 > Python - 在多线程应用程序中检测键盘中断

问题描述

我正在尝试检测键盘中断,以通知我在 2 个线程上运行的客户端服务器终止。

以下是客户端的简洁代码(但服务器相同)

class Client(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.running=True
        # some more init

    def run(self):
        while self.running:
            # do something

    def terminate(self):
        running=False

在固定的时间长度后,我可以很容易地终止这些。但是,当检测到键盘中断时,我很难终止这些组件/线程。我的问题是首先得到这个中断。

我尝试创建另一个线程来侦听键盘中断,但无法检测到中断

def main():

    components = [Server(), Client()]

    for c in components:
        c.start()

    def monitor_thread():
        try:
            while True:
                print("monitoring")
                time.sleep(1)
        except (KeyboardInterrupt, SystemExit):
            shutdown_threads(components)

    monitor = threading.Thread(target=monitor_thread)
    monitor.start()

标签: pythonmultithreading

解决方案


推荐阅读