I'm trying to create a recursive function that would launch a given function in a single thread, and in case of failure would restart it n times and then quit.
Here's my code:
def run_thread_n_times(self, func, **kwargs):
def _manage_thread(thread_restart_count):
while (thread_restart_count < MAX_THREAD_RESTART_COUNT):
try:
# runs given function
time.sleep(3)
raise Exception("fuck")
func()
except Exception:
thread_restart_count += 1
print(f"Thread crashed for {thread_restart_count} time(s)")
_manage_thread(thread_restart_count)
print(f"Thread crashed more than {MAX_THREAD_RESTART_COUNT} times, exiting...")
return
# override thread name if not in kwargs
name = self.name if "name" not in kwargs else kwargs['name']
print(f"{name}: thread started")
thread = Thread(target=_manage_thread, name=name, args=(0,))
thread.start()
I have raised an exception to simulate a similar event happening in the supplied function.
Normally I expect an output of the likes of:
Thread crashed for 1 time(s)
Thread crashed for 2 time(s)
Thread crashed for 3 time(s)
Thread crashed more than 3 times, exiting...
However, my output is the following:
Thread crashed for 1 time(s)
Thread crashed for 2 time(s)
Thread crashed for 3 time(s)
Thread crashed more than 3 times, exiting...
Thread crashed more than 3 times, exiting...
Thread crashed more than 3 times, exiting...
I do not understand why the last log is printed thrice. What am I doing wrong here?