Python - parent thread handles child threads Exception

Is there a way to get the parent who spawned the new thread to catch the exception of the generated threads? Below is a real basic example of what I'm trying to accomplish. It should stop counting when an exception occurs, but I don't know how to catch it. Are exceptions thread safe? I would love to use a module Subprocess, but I'm stuck with Python 2.3 and don't know how to do it. Perhaps using a module 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()

UPDATE

My source code was a bit misleading. He is really looking for something more:

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()

I am trying to create a watchdog timer to kill the os.system call if for some reason the program freezes.

+5
4

-

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()

. , , - 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()
+2

Python 2.3

Python 2.3 10 . ?

threading.

, , , . , .

, , , , . time.sleep() - , python Exception .

+2

, , / , , , "" ( ), - "re-raise" : http://docs.python.org/library/subprocess.html#exceptions.

( , / ), , . , () , -, "" ( try) ( ), . "" "" .

, "-" , , " " - "", "" "( ) " ", " "- / ( ). . Alex Martelli : -

, : Python

+2

, , Python 2.3, () Python 2.4, , , ( ) : Python, Popen select - -

from threading import Timer
from subprocess import Popen, PIPE

def kill_proc():
    proc.kill()

proc = Popen("count_to_10.exe", shell=True)
t = Timer(60, kill_proc)
t.start()
proc.wait()

, , .

+1

All Articles