【问题标题】:While loops and duplicate code in pythonPython中的while循环和重复代码
【发布时间】: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


【解决方案1】:
threads = [th for th in threading.enumerate() 
           if th is not threading.main_thread() or not th.isDaemon()]
while threads:
    # pseudocode:
    kill threads.pop()
    time.sleep(5)
exit()

【讨论】:

    【解决方案2】:

    我刚刚尝试了一些东西,它奏效了。这可能是一个愚蠢的解决方案,也可能是一个超级愚蠢的问题。无论如何,这就是我所做的:

    while [th for th in threading.enumerate() 
           if th is not threading.main_thread() and not th.isDaemon()]:
        sleep(5)
    exit()
    

    这很有效。我不知道我能做到这一点。哦!

    【讨论】:

    • 请注意,您实际上并不需要每次都构建整个列表。您只需要知道列表是否 包含至少一个元素。您可以为此使用anywhile any(th is not threading.main_thread() or not th.isDaemon() for th in threading.enumerate()): sleep(5)。它使用了一个生成器,所以测试只在any 找到匹配线程时执行。
    • @RobKennedy 优秀
    • @RobKennedy 我刚刚注意到那里有一个小错误。 or 应该是 andany 函数内。这是因为main-thread 本身不是守护线程,因此any 会给出误报。
    • 确保你修复它,然后。该错误一直存在于您的代码中。不过,它并没有真正改变问题或答案。
    猜你喜欢
    • 2012-07-03
    • 2020-02-22
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2021-06-23
    • 1970-01-01
    相关资源
    最近更新 更多