【发布时间】:2015-07-14 03:23:53
【问题描述】:
我的代码中有一小部分用于检查非守护进程和非主线程的活动线程。这些线程最终需要关闭,但我检查它们的部分重复如下:
threads = [th for th in threading.enumerate()
if th is not threading.main_thread() or not th.isDaemon()]
while threads:
threads = [th for th in threading.enumerate()
if th is not threading.main_thread() or not th.isDaemon()]
time.sleep(5)
exit()
我也可以尝试创建一个名为count 的变量并使用函数threading.active_count() 进行检查。我总是尽量避免创建count 变量。确实比代码重复要好。还有其他更优雅的方法吗?
【问题讨论】:
-
为什么不直接从
threads = 1开始? -
@TigerhawkT3 这正是我所说的
count的意思。这是个好主意,但我一直在寻找一种可以避免创建新变量的替代方法。 -
也许做一个函数并将列表理解粘贴在里面?那么不要重复列表理解,只需调用你的函数两次?
-
尝试子类化线程类并在模块代码中创建一个全局静态计数变量。
标签: python while-loop code-duplication