mardi 28 février 2017

Catch a thread's exception in the main thread in Python

Hi I'm new to Python and multithreaded programming. I have a script running through some test steps. Meanwhile this is running I want to create a thread that polls with an interval and reads if any processes have crashed during execution. I have a function which acquires this information. My problem is how I can throw an exception from that thread whenever I get a return value stating that a process has crashed. My current thread looks something like this:

class process_thread(threading.Thread):
  def __init__(self):
  threading.Thread.__init__(self)
  self.run_thread = True

  def run(self):
    while self.run_thread:
      if has_any_processes_crashed() == -1:
        self.run_thread = False
        raise MyStopException("A process has crashed")
      else:
        time.sleep(3)

The problem is however that the exception is only raised in that thread and not in the main thread. I want to throw the same exception there and exit the script. What I do with this thread is that I create an object before I start with all my test steps and set it as a Daemon thread by:

p_thread = process_thread()
p_thread.setDaemon(True)
p_thread.start()
  # Executing all test steps here

And then, when my test steps are done I want to kill this thread before shutting down my test simulation by:

p_thread.run_thread = False
p_thread.join()

I do not think that a Queue is possible in my scenario as I still need to execute my test steps in the main thread.

Any help is appreciated!

Aucun commentaire:

Enregistrer un commentaire