5

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?

Brad Conyers
  • 1,161
  • 4
  • 15
  • 24

1 Answers1

5

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

From the documentation:

  • thread.exit(): Raise the SystemExit exception. When not caught, this will cause the thread to exit silently.

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.

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()
pR0Ps
  • 2,752
  • 2
  • 23
  • 26
  • This is NOT a good example of the purpose of threading.Event. That class is for communicating between threads using the wait method, generally not signaling exits. In this case a simple instance variable would work just fine. – Genome May 09 '14 at 14:59
  • @Genome: Updated the answer accordingly – pR0Ps Oct 19 '15 at 15:28