2017-02-28 100 views
1

您好我是Python和多线程编程的新手。我有一个脚本通过一些测试步骤。与此同时,这是运行我想创建一个线程轮询间隔,并读取如果任何进程已崩溃在执行过程中。我有一个获取这些信息的函数。我的问题是,如果我得到一个进程崩溃,我可以从该线程抛出一个异常。我目前的线程看起来像这样:在Python的主线程中捕捉线程的异常

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") # This is the problematic line. It is only raised in this thread, not in main thread. 
     else: 
     time.sleep(3) 

但问题是,该异常只在该线程中引发,而不是在主线程中引发。我想抛出相同的异常并退出脚本。我用这个线程做的事情是,在我开始所有测试步骤并将其设置为守护程序线程之前,我创建了一个对象。当我的测试步骤完成后,我想在关闭模拟之前杀掉这个线程。

p_thread = process_thread() 
p_thread.setDaemon(True) 
p_thread.start() 

# Executing all test steps here 
# test_step_1 
do_something_1() 
# test_step_n 
do_something_n() 

p_thread.run_thread = False 
p_thread.join() 

我不认为一个队列有可能在我的方案,我仍然需要执行在主线程我的测试步骤:所有这一切都是通过做。

任何帮助表示赞赏!

回答

0

可以使用回溯模块将异常保存为变量。在正在运行,并期望例外您的线程,尝试:

import traceback 

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

    def run(self): 
     try: 
      process that may crash() 
     except: 
      self.exception_var = traceback.format_exc() 

的你在主线程访问变量:

print(self.exception_var) 

或任何你想在这里用它做。请记住,没有看到你的程序如何崩溃,我不确定这正是你想要的。这确实要求崩溃的进程实际上会导致异常,因此使用回溯。如果他们不这样做,那么你可能不得不手动提出异常。这里有一个很好的答案: Manually raising (throwing) an exception in Python

+0

这不能解决我的问题,因为如果它得到任何异常,我将不得不经常询问这个变量。然后,我不会从线程中获得任何东西,因为我可以调用常规函数来获取此信息。我需要在创建的守护线程的主线程中引发异常的东西。 –

+0

好的,你是否尝试过'thread.interrupt_main()'方法,这会在主线程中触发'KeyboardInterrupt'。链接在这里:https://docs.python.org/2/library/thread.html#thread.interrupt_main –

+0

谢谢你,那正是我之后的事,因为我没有发现任何关于提升自定义异常的事情。竖起大拇指 –