When I run a python program (2.7 or 3), I import a module that has a class that initializes some threads. The problem is whenever an uncaught exception occurs in the main thread, the main function dies yet the thread keeps running like a zombie causing the python process to never die.
What's the best way to have any uncaught exception in the main thread (or even other threads) to kill everything everywhere.
Since I often call the subprocess
module, I usually use threading.Event
to help exit cleanly. However, uncaught exceptions won't trigger those events.
Here's an example of a program where the thread just won't die....
prog1.py
#!/usr/bin/env python2.7
import threading
import modx1
mod_obj = modx1.Moddy()
raise Exception('DIE UNEXPECTEDLY')
try:
raise Exception('known problem here')
except Exception:
mod_obj.kill_event.set()
modx1.py
#!/usr/bin/env python2.7
import threading
import subprocess
from time import sleep
class Moddy():
def __init__(self):
self.kill_event = threading.Event()
self.my_thread=threading.Thread(target=self.thread_func)
self.my_thread.start()
def thread_func(self):
while not self.kill_event.is_set():
print('thread still going....')
sleep(2)
For the answer that I accepted here, I did see the solution ("threading.main_thread().is_alive()") in an unaccepted answer at the bottom of that post. But, again, this post is not a duplicate of that one. – MookiBar Jan 22 '21 at 21:16