我有一个 Python GUI,用来测试我工作的各个方面。目前我有一个“停止”按钮,可以在每个测试结束时终止进程(可以设置多个测试同时运行)。但是,有些测试需要很长时间才能运行,如果我需要停止测试,我希望它立即停止。我的想法是使用
import pdb; pdb.set_trace()
exit
但我不确定如何将其注入到下一个运行的代码行中。这可能吗?
如果是线程,则可以使用较低级别的thread
(or _thread
在Python 3)模块中通过调用杀死异常线程thread.exit()
.
来自文档:
- thread.exit():提高系统退出例外。没被抓到的时候,
这将导致线程静默退出。
一种更干净的方法(取决于处理的设置方式)是使用实例变量向线程发出停止处理并退出的信号,然后调用join()方法从主线程等待,直到线程退出。
Example:
class MyThread(threading.Thread):
def __init__(self):
super(MyThread, self).__init__()
self._stop_req = False
def run(self):
while not self._stop_req:
pass
# processing
# clean up before exiting
def stop(self):
# triggers the threading event
self._stop_req = True;
def main():
# set up the processing thread
processing_thread = MyThread()
processing_thread.start()
# do other things
# stop the thread and wait for it to exit
processing_thread.stop()
processing_thread.join()
if __name__ == "__main__":
main()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)