python - 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()
解决方案
推荐阅读
- arrays - 如何连接以逗号分隔的命名范围的返回值
- mysql - B树的最小占用率是多少?
- c# - 如何从 Ninja Trader 的操作中使用 C# 制作 JSON 帖子?
- javascript - 如何在运行测试用例之前正确初始化/加载 aurelia-dialog 插件?
- google-chrome - 将不安全的来源视为安全
- javascript - 关于在 JavaScript 中调用函数,哪一个是正确的?
- c++11 - 为什么委托给默认构造函数不为零初始化成员变量
- rabbitmq - 我更改了 rabbitmq 的磁盘限制,现在无法重新启动它。
- react-native - 反应导航不起作用
- html - 如何确保我的标题图像对所有高度和宽度都有响应?