更新:在当前的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)