如何从 Tkinter 窗口立即停止 Python 进程? [英] How do I stop a Python process instantly from a Tkinter window?

查看:56
本文介绍了如何从 Tkinter 窗口立即停止 Python 进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Python GUI that I use to test various aspects of my work. Currently I have a "stop" button which kills the process at the end of each test (there can be multiple tests set up to run at once). However, some tests take a long time to run and if I need to stop the test I would like it to stop instantly. My thoughts are to use

import pdb; pdb.set_trace()
exit

但我不确定如何将其注入下一个运行代码行.这可能吗?

But I'm not sure how I would inject this into the next run line of code. Is this possible?

推荐答案

如果是线程,可以使用低级的thread(或者Python 3中的_thread) 模块通过调用 thread.exit() 以异常方式终止线程.

If it's a thread, you can use the lower-level thread (or _thread in Python 3) module to kill the thread with an exception by calling thread.exit().

来自文档:

  • thread.exit():引发 SystemExit 异常.没抓到的时候这将导致线程静默退出.
  • thread.exit(): Raise the SystemExit exception. When not caught, this will cause the thread to exit silently.

更简洁的方法(取决于您的处理方式)是使用实例变量通知线程停止处理并退出,然后调用 join() 方法等待线程退出.

A cleaner method (depending on how your processing is set up) would be to signal the thread to stop processing and exit using an instance variable, then calling the join() method from your main thread to wait until the thread exits.

示例:

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

这篇关于如何从 Tkinter 窗口立即停止 Python 进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆