python怎么通过键盘中断程序_python – Catch键盘正在等待事件的程序中断

更新:在当前的Python 3上,finished_event.wait()适用于我的Ubuntu机器(从Python 3.2开始).您不需要指定timeout参数,使用Ctrl C中断它.您需要在CPython 2上传递timeout参数.

这是一个完整的代码示例:

#!/usr/bin/env python3

import threading

def f(event):

while True:

pass

# never reached, otherwise event.set() would be here

event = threading.Event()

threading.Thread(target=f, args=[event], daemon=True).start()

try:

print('Press Ctrl+C to exit')

event.wait()

except KeyboardInterrupt:

print('got Ctrl+C')

可能有bugs与Ctrl+C相关.测试它是否适用于您的环境.

旧民意调查答案:

您可以尝试允许解释器运行主线程:

while not finished_event.wait(.1): # timeout in seconds

pass

如果您只想等到子线程完成:

while thread.is_alive():

thread.join(.1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值