Wednesday, 11 September 2013

Python - print traceback and stop execution on worker exception

Python - print traceback and stop execution on worker exception

In my application, I'm using several worker threads and a mainloop which
is a part of external module and can't be modified. When a worker thread
raises an exception, the app should stop the mainloop, do some cleanup,
print the worker exception traceback and exit. The mainloop should be
stopped by raising ExitMainLoop exception.
Here's an example code:
from time import sleep
from threading import Thread
class MyException(BaseException):
pass
class ExitMainLoop(BaseException):
pass
def main_loop():
print('started main loop')
try:
while True:
print('.')
sleep(1)
except ExitMainLoop:
pass
def do_work():
print('started worker thread')
sleep(5)
raise MyException
def main():
worker = Thread(target=do_work)
worker.daemon = True
worker.start()
main_loop()
if __name__ == '__main__':
main()

No comments:

Post a Comment