【发布时间】:2011-10-15 13:33:18
【问题描述】:
有没有办法让产生新线程的父线程捕获产生的线程异常?下面是我想要完成的一个真实的基本示例。当引发异常时它应该停止计数,但我不知道如何捕捉它。异常线程安全吗?我希望能够使用 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()
更新
我的原始代码有点误导。它真的在寻找更像这样的东西:
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()
如果程序由于某种原因挂起,我正在尝试创建一个看门狗来终止 os.system 调用。
【问题讨论】:
-
你想达到什么目的,看起来你想从子线程向父线程发送一些事件?还是你真的想传递异常?
-
我正在尝试终止
os.system调用,如果它需要很长时间,很可能不是正确的方法。
标签: python multithreading exception parent-child watchdog