完成所有 Python 单元测试后拆除所有打开的线程

pas*_*oop 8 python testing multithreading

该线程详细讨论了为什么终止线程不是一个好主意。当我们谈论一个实际的计划时,我同意。我正在为几个组件编写单元测试以及它们之间的一些集成测试。有些需要线程。当测试失败时,某些线程保持打开状态,并锁定在.get()队列的调用中。这会导致整个测试套件陷入困境并且不完整。我正在运行ptw(pytest watch) 或 pytest 的自定义循环,以inotifywait监视文件中的更改以重新运行套件。

当所有测试完成后,我希望套件杀死任何剩余的线程以完成循环,而不是卡在由于测试失败而刚刚打开的某个线程上。这可能吗?

Sra*_*raw 8

没有一种优雅的方法来停止线程,但您可以将它们设置daemonTrue.

代码片段:

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
Run Code Online (Sandbox Code Playgroud)

然后它们将在主线程终止时终止。