您好我是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()
我不認爲一個隊列有可能在我的方案,我仍然需要執行在主線程我的測試步驟:所有這一切都是通過做。
任何幫助表示讚賞!
這不能解決我的問題,因爲如果它得到任何異常,我將不得不經常詢問這個變量。然後,我不會從線程中獲得任何東西,因爲我可以調用常規函數來獲取此信息。我需要在創建的守護線程的主線程中引發異常的東西。 –
好的,你是否嘗試過'thread.interrupt_main()'方法,這會在主線程中觸發'KeyboardInterrupt'。鏈接在這裏:https://docs.python.org/2/library/thread.html#thread.interrupt_main –
謝謝你,那正是我之後的事,因爲我沒有發現任何關於提升自定義異常的事情。豎起大拇指 –