Python线程退出代码 [英] Python thread exit code

查看:102
本文介绍了Python线程退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有办法判断线程是否正常退出或由于异常而退出?

Is there a way to tell if a thread has exited normally or because of an exception?

推荐答案

如前所述,Thread类的包装可以捕获该状态.这是一个例子.

As mentioned, a wrapper around the Thread class could catch that state. Here's an example.

>>> from threading import Thread
>>> class MyThread(Thread):
    def run(self):
        try:
            Thread.run(self)
        except Exception as err:
            self.err = err
            pass # or raise err
        else:
            self.err = None


>>> mt = MyThread(target=divmod, args=(3, 2))
>>> mt.start()
>>> mt.join()
>>> mt.err
>>> mt = MyThread(target=divmod, args=(3, 0))
>>> mt.start()
>>> mt.join()
>>> mt.err
ZeroDivisionError('integer division or modulo by zero',)

这篇关于Python线程退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆