问题描述
如果我在无限循环中有一个线程,有没有办法在主程序结束时终止它(例如,当我按 + )?
If I have a thread in an infinite loop, is there a way to terminate it when the main program ends (for example, when I press +)?
推荐答案
选中此问题.正确答案对如何以正确的方式终止线程有很好的解释:是否有任何方法可以杀死Python中的线程?
Check this question. The correct answer has great explanation on how to terminate threads the right way:Is there any way to kill a Thread in Python?
要使线程在键盘中断信号(ctrl + c)上停止,您可以在退出之前捕获异常"KeyboardInterrupt"并进行清除.像这样:
To make the thread stop on Keyboard Interrupt signal (ctrl+c) you can catch the exception "KeyboardInterrupt" and cleanup before exiting. Like this:
try:
start_thread()
except (KeyboardInterrupt, SystemExit):
cleanup_stop_thread()
sys.exit()
这样,您可以控制程序突然终止时的操作.
This way you can control what to do whenever the program is abruptly terminated.
您还可以使用内置的信号模块,该模块允许您设置信号处理程序(在您的特定情况下为SIGINT信号): http://docs.python.org/library/signal.html
You can also use the built-in signal module that lets you setup signal handlers (in your specific case the SIGINT signal): http://docs.python.org/library/signal.html
这篇关于主程序结束时如何终止线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!