简体   繁体   中英

Python How Do I Refresh Psutil Result?

I'm trying to make python script to print top 5 processes by cpu/memory usage every minute. However, the cpu result doesn't seem to change when it loops.

How can I get new set of measurements for cpu when it loops?

My code is below.

Thank you for your help!

import psutil
import time;
from functools import cmp_to_key

def log(line):
    print(line)
    with open("log.txt", "a") as f:
        f.write("{}\n".format(line))

def cmpCpu(a, b):
    a = a['cpu']
    b = b['cpu']
    if a > b:
        return -1
    elif a == b:
        return 0
    else:
        return 1

def cmpMemory(a, b):
    a = a['memory']
    b = b['memory']
    if a > b:
        return -1
    elif a == b:
        return 0
    else:
        return 1

def getInfo(pid):
    p = psutil.Process(pid)
    name = p.name()
    cpu = p.cpu_percent()
    memory = int(p.memory_info().rss/1024/1024)
    return {'name':name, 'cpu':cpu, 'memory':memory}

while True:
    localtime = time.localtime(time.time())
    timestamp = str(localtime.tm_hour)+":"+str(localtime.tm_min)
    log(timestamp)

    processes = []
    for i in psutil.pids():
        processes.append(getInfo(i))

    #Sort by cpu usage
    processes.sort(key=cmp_to_key(cmpCpu))
    for i in range(5):
        info = processes[i]
        info = info['name']+", "+str(info['cpu'])+"%"
        log(info)

    #Sort by memory usage
    processes.sort(key=cmp_to_key(cmpMemory))
    for i in range(5):
        info = processes[i]
        info = info['name']+", "+str(info['memory'])+"MB"
        log(info)

    time.sleep(60)

It seems like psutil.process_iter is the answer. The code below works.

import psutil
import time;
from functools import cmp_to_key

def log(line):
    print(line)
    with open("log.txt", "a") as f:
        f.write("{}\n".format(line))

def cmpCpu(a, b):
    a = a['cpu']
    b = b['cpu']
    if a > b:
        return -1
    elif a == b:
        return 0
    else:
        return 1

def cmpMemory(a, b):
    a = a['memory']
    b = b['memory']
    if a > b:
        return -1
    elif a == b:
        return 0
    else:
        return 1

while True:
    localtime = time.localtime(time.time())
    timestamp = str(localtime.tm_hour)+":"+str(localtime.tm_min)
    log(timestamp)

    #Collect information for each process
    processes = []
    for proc in psutil.process_iter(attrs=['name', 'cpu_percent', 'memory_info']):
        processes.append({'name': proc.info['name'], 'cpu': proc.info['cpu_percent'], 'memory': int(proc.info['memory_info'].rss/1024/1024)})

    #Sort by cpu usage
    log("CPU:")
    processes.sort(key=cmp_to_key(cmpCpu))
    for i in range(5):
        info = processes[i]
        info = info['name']+", "+str(info['cpu'])+"%"
        log(info)

    #Sort by memory usage
    log("Memory:")
    processes.sort(key=cmp_to_key(cmpMemory))
    for i in range(5):
        info = processes[i]
        info = info['name']+", "+str(info['memory'])+"MB"
        log(info)

    time.sleep(60)

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