Python如何刷新Psutil结果?

时间:2018-12-14 15:24:39

标签: python psutil

我正在尝试使python脚本每分钟通过cpu /内存使用情况来打印前5个进程。但是,cpu结果在循环时似乎并没有改变。

当cpu循环时如何获得新的测量值?

我的代码在下面。

谢谢您的帮助!

addfiglab <- function(lab, xl = par()$mar[2], yl = par()$mar[3], cex = 1) {

  text(x = line2user(xl, 2), y = line2user(yl, 3), 
       lab, xpd = NA, font = 2, cex = cex, adj = c(0, 1))

}

line2user <- function(line, side, outer = FALSE) {
  unit <- if (outer) "nic" else "npc"
  lh <- par('cin')[2] * par('cex') * par('lheight')
  x_off <- diff(grconvertX(c(0, lh), 'inches', unit))
  y_off <- diff(grconvertY(c(0, lh), 'inches', unit))
  switch(side,
         `1` = grconvertY(-line * y_off, unit, 'user'),
         `2` = grconvertX(-line * x_off, unit, 'user'),
         `3` = grconvertY(1 + line * y_off, unit, 'user'),
         `4` = grconvertX(1 + line * x_off, unit, 'user'),
         stop("Side must be 1, 2, 3, or 4", call.=FALSE))
}

layout(matrix(c(rep(1, 9), 2:10), ncol = 3, byrow = TRUE))
plot(1:10); addfiglab("A")
for (i in 2:10) {plot(i); addfiglab(LETTERS[i])} 

1 个答案:

答案 0 :(得分:0)

似乎psutil.process_iter就是答案。下面的代码有效。

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)