gpt4 book ai didi

python - 如何从 Tkinter 窗口立即停止 Python 进程?

转载 作者:太空狗 更新时间:2023-10-30 01:09:35 25 4
gpt4 key购买 nike

我有一个 Python GUI,用于测试我工作的各个方面。目前我有一个“停止”按钮,可以在每次测试结束时终止进程(可以同时运行多个测试)。但是,有些测试需要很长时间才能运行,如果我需要停止测试,我希望它立即停止。我的想法是用

import pdb; pdb.set_trace()
exit

但我不确定如何将其注入(inject)到下一行运行的代码中。这可能吗?

最佳答案

如果它是一个线程,你可以使用较低级别的thread(或Python 3中的_thread)模块通过调用异常杀死线程thread.exit().

来自documentation :

  • thread.exit():引发SystemExit异常(exception)。没抓到的时候,这将导致线程静默退出。

更简洁的方法(取决于您的处理设置方式)是使用实例变量向线程发出停止处理并退出的信号,然后调用 join()方法从主线程等待直到线程退出。

例子:

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()

关于python - 如何从 Tkinter 窗口立即停止 Python 进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11938109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com