Python循环控制。避免悬挂环

标签 python loops

这是我在上一个关于循环更新数据的问题之前遇到的一个新问题。我有一个小脚本,读取 CPU 时间并在达到一定百分比时闪烁 LED,当我达到 100% CPU 时,我希望 LED 持续闪烁,所以我将其放入 while 循环中,但脚本将挂起并停留一旦到达那里,就会在 100 处,但如果它下降,脚本将卡在 100 处并且不会更新,我在 while 循环内编写了一个嵌套循环来更新 CPU,但仍然卡在这里。我知道它卡在我拥有的 while 循环上,但我需要 while 循环来保持连续闪烁,有没有办法在更新 cpu 时间时保持 while 循环?

这就是我所拥有的:

while True:
    cpu_time = psutil.cpu_percent(interval=1,percpu=False)
    print cpu_time

    if cpu_time>0:
        led_blink()
        print cpu_time
    elif cpu_time>0 and cpu_time<10:
        led_blink()
        print cpu_time
  #same elif loops for for 30%, 50%, 75% until 100% i get a hang
    elif cpu_time>90:
        while cpu_time>90:
              print cpu_time
              led_blink()
              if cpu_time < 90:
                  break
                  #also tried using 'continue' but same result

最佳答案

您的嵌套 if 语句永远不会计算为 true。外循环仅在 cpu_time > 90 时运行但内心if检查cpu_time < 90当你处于那个循环中时,这永远不会是真的。

由于这是跳出循环的唯一方法,因此循环是无限的。尝试重新设计你的逻辑。

关于Python循环控制。避免悬挂环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32699395/

相关文章:

php - linux ubuntu 18.04 灯 php 和 python cgi

python - Python 中的循环问题

c - 为什么我调用这个函数8次,结果都是上次的?在 C 中

python - Algos - 从 Python 中的整数列表中删除极值?

java - 简单的java循环写入数据库会导致内存不足异常

python - 根据另外 2 个列表对齐 2 个 python 列表

python 3 : install in virtualenv fails

python - FormName 没有属性 'error_messages'

python - Jupyter笔记本: module not found even after pip install

python - 如何按定义的顺序遍历 Python 字典?