'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?



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sraw
Solution 2 karthikeayan