Reputation: 964
This is a new issue I am running into prior to my last question about updating data in loops. I have a small script reading in CPU time and flashing LED's when it hits a certain percentage, when I hit 100% CPU I want the LED's to be continuously blinking, so i put it in a while loop, but the script will hang and stay at 100 once it reaches there, but if it goes down the script will hang at 100 and won't update, I wrote a nested loop inside the while loop to update the CPU but still hangs here. I know it is hanging from that while loop that I have, but I need to while loop to keep the continuous flashing, is there anyway to keep that while loop while updating the cpu time?
this what I had:
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
Upvotes: 2
Views: 808
Reputation: 900
Review your conditions. Your code will either run the code block under if cpu_time>0:
, or do nothing.
But there's a more fundamental issue with this loop. By default, computer software is going to want to do as much as it can as fast as the operating system will allow it to. Your loop is using 100% CPU on its own.
Since this is a polling loop, you need to tell the thread to sleep.
import time
time.sleep(1) # sleeps for 1 second
A--- is right about no update occurring in the while cpu_time>90
loop, but even if an update did occur, you would be stuck in that loop by virtue of the polling loop running at full speed.
Here's how I'd write it.
import time
while True:
cpu_time = psutil.cpu_percent(interval=1,percpu=False)
# put cpu_time conditions here,
# but right now they're all doing the same thing, so...
print cpu_time
led_blink()
time.sleep(1)
Upvotes: 0
Reputation: 920
a) You should change elif cpu_time>90
to either if cpu_time>90:
or elif cputime>0 and cpu_time>90
b) Your inner loop is broken
c) Maybe you want something like this?
def blink(cpu_time, max_time):
assert cpu_time > 0, "Internal error!"
print cpu_time
flag = False
if cpu_time < max_time:
led_blink()
flag = True
return flag
outflag = True
max_time = 90
while outflag:
cpu_time = psutil.cpu_percent(interval=1,percpu=False)
outflag = blink(cpu_time, max_time)
Upvotes: 1
Reputation: 2593
Your nested if statement will never evaluate to true. The outer loop only runs while cpu_time > 90
but the inner if
checks cpu_time < 90
which will never be true when you're in that loop.
Since that's the only way to break out of your loop, the loop is infinite. Try reworking your logic.
Upvotes: 3