Python thread exit code

后端 未结 3 702
太阳男子
太阳男子 2021-02-19 03:14

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

3条回答
  •  甜味超标
    2021-02-19 04:09

    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',)
    

提交回复
热议问题