Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tearing down any open Threads after completing all Python Unittests

this thread discusses at great length why it is not a good idea to kill threads. And I agree when we are talking about an actual program. I am writing unit tests for several components as well as some integration tests between them. Some require threading. When tests fail, some threads stay open, locked in a .get() call of a queue. This causes the whole test suite to get stuck and not complete. I am running either ptw (pytest watch) or a custom loop of pytest with inotifywait to watch for changes in my files to rerun the suite.

When all tests have completed, I want the suite to kill any remaining threads to complete the loop and not be stuck on a thread somewhere that is just open because of a test failure. Is this possible?

like image 603
pascalwhoop Avatar asked May 21 '26 07:05

pascalwhoop


2 Answers

There isn't an elegant way to stop a thread, but you can set their daemon to True.

code snippet:

import threading

all_child_threads = [thread for thread in threading.enumerate() if thread != threading.main_thread()]
for thread in all_child_threads:
    thread.daemon = True

Then they will terminate when main thread terminates.

like image 159
Sraw Avatar answered May 23 '26 21:05

Sraw


Based on Sraw's response, I was able to set the thread to terminate when the main thread terminates, passing daemon=True when starting the thread:

threading.Thread(target=method, daemon=True).start()

So when I run my unit tests, for example, it would end the execution instead of keep running forever since there's still a thread running.

like image 36
Bipe Avatar answered May 23 '26 20:05

Bipe