Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python thread exit code

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

like image 979
Jiayao Yu Avatar asked Jun 12 '09 13:06

Jiayao Yu


People also ask

How do you exit a thread in Python?

In order to kill a thread, we use hidden function _stop() this function is not documented but might disappear in the next version of python.

How do you start and stop a thread in Python?

You can't actually stop and then restart a thread since you can't call its start() method again after its run() method has terminated. However you can make one pause and then later resume its execution by using a threading. Condition variable to avoid concurrency problems when checking or changing its running state.

How do you change the exit code in Python?

You can set an exit code for a process via sys. exit() and retrieve the exit code via the exitcode attribute on the multiprocessing.


1 Answers

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',)
like image 57
2 revs, 2 users 94% Avatar answered Sep 30 '22 19:09

2 revs, 2 users 94%