python主线程捕获子线程的方法

yipeiwu_com6年前Python基础

最近,在做一个项目时遇到的了一个问题,主线程无法捕获子线程中抛出的异常。

先看一个线程类的定义

''''' 
Created on Oct 27, 2015 
 
@author: wujz 
''' 
import threading 
 
class runScriptThread(threading.Thread): 
 def __init__(self, funcName, *args): 
  threading.Thread.__init__(self) 
  self.args = args 
  self.funcName = funcName 
  
 def run(self): 
  try: 
   self.funcName(*(self.args)) 
  except Exception as e: 
   raise e 

很简单,传入要调用的方法,并启用一个新的线程来运行这个方法。

在主线程中,启动这个线程类的一个对象时,这要声明一个对象然后启动就可以了,示例如下

import runScriptThread,traceback 
 
if __name__=='__main__': 
 sth = 'hello world' 
 try: 
  aChildThread = runScriptThread(printSth, sth) 
  aChildThread.start() 
  aChildThread.join() 
 except Exception as e: 
  print(str(traceback.format_exc())) 

但是这样的代码,main方法中无法捕获子线程中的异常,原因在于start()方法将为子线程开辟一条新的栈,main方法的栈因此无法捕获到这一异常。

解决方法很简单,就是通过设置一个线程是否异常退出的flag的成员变量,当线程异常退出时,对其作一标记。然后在主线程中检查改线程运行结束后该标志位的值,如果异常,再通过sys和traceback回溯异常信息,然后抛出即可。改写后的异常类:

''''' 
Created on Oct 27, 2015 
 
@author: wujz 
''' 
import threading,traceback,sys 
 
class runScriptThread(threading.Thread): #The timer class is derived from the class threading.Thread 
 def __init__(self, funcName, *args): 
  threading.Thread.__init__(self) 
  self.args = args 
  self.funcName = funcName 
  self.exitcode = 0 
  self.exception = None 
  self.exc_traceback = '' 
  
 def run(self): #Overwrite run() method, put what you want the thread do here 
  try: 
   self._run() 
  except Exception as e: 
   self.exitcode = 1  # 如果线程异常退出,将该标志位设置为1,正常退出为0 
   self.exception = e 
   self.exc_traceback = ''.join(traceback.format_exception(*sys.exc_info())) #在改成员变量中记录异常信息 
  
 def _run(self): 
  try: 
   self.funcName(*(self.args)) 
  except Exception as e: 
   raise e 

改写后的主线程:

import runScriptThread,traceback 
 
if __name__=='__main__': 
 sth = 'hello world' 
 try: 
  aChildThread = runScriptThread(printSth, sth) 
  aChildThread.start() 
  aChildThread.join() 
 except Exception as e: 
  print(aChildThread.exc_traceback) 

以上全部为本篇文章的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用Python正则表达式操作文本数据的方法

什么是正则表达式 正则表达式,是简单地字符的序列,可指定特定的搜索模式。正则表达式已存在很长一段时间,并且它本身就是计算机科学的一个领域。 在 Python中,使用Python的内置r...

使用Python更换外网IP的方法

在进行数据抓取时,经常会遇到IP被限制的情况,常见的解决方案是搭建代理IP池,或购买IP代理的服务。除此之外,还有一个另外的方法就是使用家里的宽带网络进行抓取。由于家里的宽带每次断开重新...

python-itchat 统计微信群、好友数量,及原始消息数据的实例

python-itchat 统计微信群、好友数量,及原始消息数据的实例

参考来自:https://itchat.readthedocs.io/zh/latest/api/ #coding=utf-8 import itchat from itchat.c...

Python中函数参数调用方式分析

本文实例讲述了Python中函数参数调用方式。分享给大家供大家参考,具体如下: Python中函数的参数是很灵活的,下面分四种情况进行说明。 (1) fun(arg1, arg2, .....

详解Django-restframework 之频率源码分析

详解Django-restframework 之频率源码分析

一 前言 经过权限判断之后就是进行频率的判断了,而频率的判断和权限又不一样,认证、权限和频率的执行流程都差不多,使用配置里面的相关类来进行判断。而不和认证和权限一样,频率的配置没有,查看...