Python - 让父线程处理子线程异常

Das*_*Rot 5 python multithreading exception parent-child watchdog

有没有办法让产生新线程的父级捕获产生的线程异常?以下是我想要完成的一个真实的基本示例.当引发Exception时它应该停止计数,但我不知道如何捕获它.异常线程安全吗?我希望能够使用该Subprocess模块,但我不习惯使用Python 2.3,我不知道如何做到这一点.可能使用该threading模块?

import time
import thread

def test(): 
    try:
        test = thread.start_new_thread(watchdog, (5,))
        count(10)
    except:
        print('Stopped Counting')

def count(num):
    for i in range(num):
        print i
        time.sleep(1)

def watchdog(timeout):
    time.sleep(timeout)
    raise Exception('Ran out of time')

if __name__ == '__main__':
    test()
Run Code Online (Sandbox Code Playgroud)

UPDATE

我的原始代码有点误导.它真的在寻找更像这样的东西:

import time
import thread
import os

def test(): 
    try:
        test = thread.start_new_thread(watchdog, (5,))
        os.system('count_to_10.exe')
    except:
        print('Stopped Counting')

def watchdog(timeout):
    time.sleep(timeout)
    raise Exception('Ran out of time')

if __name__ == '__main__':
    test()
Run Code Online (Sandbox Code Playgroud)

我试图创建一个看门狗来杀死os.system调用,如果该程序由于某种原因挂起.

小智 3

为什么不是这样的东西

def test(): 
    def exeption_cb():
        os._exit()
    test = thread.start_new_thread(watchdog, (5, exception_cb))
    os.system('count_to_10.exe')
    print('Stopped Counting')

def watchdog(timeout, callback):
    time.sleep(timeout)
    callback()
Run Code Online (Sandbox Code Playgroud)

这将停止整个过程。您可以做的另一件事是在不同的线程中启动 os.system,然后倒计时,然后终止该线程。像这样的事情,

def system_call():
    os.system('count_to_10.exe')

system_thread = thread.start_new_thread(system_call)
time.sleep(timeout)
system_thread.kill()
Run Code Online (Sandbox Code Playgroud)