无法在 Windows 上使用键盘 Ctrl+C 中断线程 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()

你使线程成为一个守护进程,但你还需要保持你的"主"线程处于活动状态以侦听信号或键盘中断

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

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

最新更新