简体   繁体   中英

Python: Creating a Loop to update data

I have a small python script this is printing out how much CPU usage the machine is using, I am running into an issue, that it won't update after there is a change in percentage, I put it under an infinite while loop but it stays at the last percent that was recorded, here is my code any help or advice would be splendid:

cpu_time = psutil.cpu_percent(interval=1,percpu=False)
var=1
while var==1:
    if cpu_time < 10:
        print "CPU usage: "+str(cpu_time)
    elif cpu_time <=25:
        print "CPU usage: "+str(cpu_time)

etc... for 50, 75 and 90 percent

As it is now, cpu_time is never changing. You want to update the cpu_time inside the loop:

while True:
    cpu_time = psutil.cpu_percent(interval=1,percpu=False)
    if cpu_time < 10:
        print "CPU usage: "+str(cpu_time)
    elif cpu_time <=25:
        print "CPU usage: "+str(cpu_time)

you need to refresh the cpu_time value : put it inside the loop

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

    if cpu_time < 10:
        print "CPU usage: "+str(cpu_time)
    elif cpu_time <=25:
        print "CPU usage: "+str(cpu_time)

You need to call the function that returns the CPU data into the loop, not outside:

while True:
    cpu_time = psutil.cpu_percent(interval=1,percpu=False)
    if cpu_time < 10:
        print "CPU usage: "+str(cpu_time)
    elif cpu_time <=25:
        print "CPU usage: "+str(cpu_time)

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM