【问题标题】:How do I stop a Python process instantly from a Tkinter window?如何从 Tkinter 窗口立即停止 Python 进程?
【发布时间】:2012-08-09 21:46:04
【问题描述】:

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

import pdb; pdb.set_trace()
exit

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

【问题讨论】:

  • 您是要停止 python 进程还是 python 线程?

标签: python tkinter inject


【解决方案1】:

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

来自documentation:

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

一种更简洁的方法(取决于您的处理设置方式)是使用实例变量通知线程停止处理并退出,然后从主线程调用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()

【讨论】:

  • 这不是 threading.Event 目的的一个很好的例子。该类用于使用等待方法在线程之间进行通信,通常不发出退出信号。在这种情况下,一个简单的实例变量就可以正常工作。
  • @Genome:相应地更新了答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-26
  • 2014-02-23
相关资源
最近更新 更多