2017-02-28 95 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

謝謝你,那正是我之後的事,因爲我沒有發現任何關於提升自定義異常的事情。豎起大拇指 –