以下是关于python来获取服务器每颗CPU使用率的使用脚本。

#!/usr/bin/env python
# -*- coding: utf-8 -*- import re,time def _read_cpu_usage():
"""Read the current system cpu usage from /proc/stat"""
statfile = "/proc/stat"
cpulist = []
try:
f = open(statfile, 'r')
lines = f.readlines()
except:
print "ERROR: Can not open %s,The system cannot continue to run" % (statfile)
return []
for line in lines:
tmplist = line.split()
if len(tmplist) < 5:
continue
for b in tmplist:
m = re.search(r'cpu\d+',b)
if m is not None:
cpulist.append(tmplist)
f.close()
return cpulist def get_cpu_usage():
cpuusage = {}
cpustart = {}
cpuend = {}
linestart = _read_cpu_usage()
if not linestart:
return 0
for cpustr in linestart:
usni=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])+long(cpustr[5])+long(cpustr[6])+long(cpustr[7])+long(cpustr[4])
usn=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])
cpustart[cpustr[0]] = str(usni)+":"+str(usn)
sleep = 2
time.sleep(sleep)
lineend = _read_cpu_usage()
if not lineend:
return 0
for cpustr in lineend:
usni=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])+long(cpustr[5])+long(cpustr[6])+long(cpustr[7])+long(cpustr[4])
usn=long(cpustr[1])+long(cpustr[2])+long(cpustr[3])
cpuend[cpustr[0]] = str(usni)+":"+str(usn)
for line in cpustart:
start = cpustart[line].split(':')
usni1,usn1 = float(start[0]),float(start[1])
end = cpuend[line].split(':')
usni2,usn2 = float(end[0]),float(end[1])
cpuper=(usn2-usn1)/(usni2-usni1)
cpuusage[line] = int(100*cpuper) return cpuusage if __name__ == '__main__':
a = get_cpu_usage()
print a

最新文章

  1. qt中添加Q_OBJECT报错的问题
  2. Collider Collision 区别
  3. 安装Adobe Flash Player
  4. 携程Android App插件化和动态加载实践
  5. [Effective JavaScript 笔记] 第11条:熟练掌握闭包
  6. 【NHibernate】应用层面需要掌握的知识汇总
  7. Android_AsyncTask_json
  8. kettle 连接 mysql 出错 Driver class &#39;org.gjt.mm.mysql.Driver&#39; could not be found, make sure the ……
  9. 不同服务器数据库之间的数据操作 sp_addlinkedserver
  10. 深入理解计算机系统chapter9
  11. 【精解】EOS智能合约演练
  12. struct2 拿到url的方法
  13. WCF 改成 restful api
  14. socket-WebSocket-HttpListener-TcpListener服务端客户端的具体使用案例
  15. JDK8新增接口的默认方法与静态方法
  16. boost asio 学习(七) 网络基础 连接器和接收器(TCP示例)
  17. 力扣(LeetCode) 104. 二叉树的最大深度
  18. Mysql 创建数据库命令
  19. Java学习——使用Static修饰符
  20. PHP下进行XML操作(创建、读取)

热门文章

  1. VoHelper
  2. initialSize,maxTotal,maxIdle,minIdle,maxWaitMillis
  3. tableviewcell 系统工具删除:左滑删除,选中多个删除
  4. Mongo数据模型
  5. OC:关于Itunes你了解多少?
  6. Mathematics for Computer Graphics数学在计算机图形学中的应用 [转]
  7. javaScript return false
  8. chart.js接口开发:X轴步长和Labels旋转角
  9. EasyMock问题总结
  10. MVC ajax 上传文件