牛骨文教育服务平台(让学习变的简单)
博文笔记

python psutil跨平台监控系统或进程信息(CPU,mem)

创建时间:2016-04-11 投稿人: 浏览次数:202

psutil is a cross-platform library for retrieving information onrunning processes and system utilization (CPU, memory, disks, network)in Python.

https://pypi.python.org/pypi/psutil


#!/usr/bin/python
#coding=utf-8

import sys
import psutil

def main(process_name):
    list_mem = []
    list_cpu = []
    max_mem = 0
    max_cpu = 0
    ave_mem = 0
    ave_cpu = 0
    
    try:
        while True:
            try:
                for p in psutil.process_iter():
                    if p.name() == process_name:
                        #print p.memory_info()
                        mem = p.memory_info()[0]#rss, 可参考help(psutil._pswindows.pmem)
                        cpu = p.cpu_percent(interval=1)
                        print cpu
                        list_mem.append(mem)
                        list_cpu.append(cpu)
            except psutil.NoSuchProcess:
                continue
    except KeyboardInterrupt:
        print ">>>KeyboardInterrupt"
    
    
    total_mem = 0
    total_cpu = 0
    for mem in list_mem:
        total_mem += mem
        if mem > max_mem:
            max_mem = mem
    ave_mem = total_mem/len(list_mem)
    
    for cpu in list_cpu:
        total_cpu += cpu
        if cpu > max_cpu:
            max_cpu = cpu
    ave_cpu = total_cpu/len(list_cpu)
    
    print max_mem/1024, ave_mem/1024
    print max_cpu, ave_cpu
            
if __name__ == "__main__":
    main(sys.argv[1])


声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。