代码之家  ›  专栏  ›  技术社区  ›  Dmitrii Vinokurov

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

  •  0
  • Dmitrii Vinokurov  · 技术社区  · 6 年前

    我无法使用中断我的线程化Python生产应用程序 Ctrl键 + C 在Windows上,它继续运行,尝试了异常和信号处理。这是非常简化的代码版本,不会中断。单线程应用程序终止良好,与多线程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()
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Fluffy    6 年前

    您将线程设置为守护进程,但还需要保持“主”线程处于活动状态,以侦听信号或键盘中断

    使用信号的简单工作实现:

    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()