您的位置:首页 > 编程语言 > Python开发

python写的树莓派实时监控温度,cpu使用率的小程序

2017-02-19 03:44 441 查看
楼主纯新手,最近思考着怎么写一个监控树莓派温度和CPU使用率的小程序。参考了网上

https://gist.github.com/582033/b94dc1d4941f63bb28d837fa9c72f08d

以及

http://blog.csdn.net/huayucong/article/details/50389910

的程序。

发现对于CPU使用率这一方法,发现两个问题:

1.使用uptime
得到的并不直观而且和实际我想得到的cpu总使用率有区别;

2.使用linux的top命令,得到的是一个不会变化的定值,%Cpu(s)得到的是定值。

谷歌后发现,原因可以参考 http://unix.stackexchange.com/questions/69185/getting-cpu-usage-same-every-time/90904

最后使用2中user115023
用户的回答,解析/proc/stat中的内容计算cpu使用率。

Linux中shell命令如下:

cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{print ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5) "%"}'


此处其实为一个略简化计算方法,原理见

http://www.blogjava.net/fjzag/articles/317773.html

最终代码如下:

#!/usr/bin/env python
import os
import time

#show raspberry temperature,CPU,memory

def getCPUtemp():
temp = os.popen('vcgencmd measure_temp').readline()
tempfloat = float(temp.replace('temp=','').replace('\'C\n',''))
print 'CPU Temperature is now %.1f Centigrade' %tempfloat
if tempfloat > 60:
print 'CPU Temperature is too high, pls cool it down'

def getCPUusage():
#calculate CPU with two short time, time2 - time1
time1 = os.popen('cat /proc/stat').readline().split()[1:5]
time.sleep(0.2)
time2 = os.popen('cat /proc/stat').readline().split()[1:5]
deltaUsed = int(time2[0])-int(time1[0])+int(time2[2])-int(time1[2])
deltaTotal = deltaUsed + int(time2[3])-int(time1[3])
cpuUsage = float(deltaUsed)/float(deltaTotal)*100
print 'CPU Usage is now %.1f' %cpuUsage +'%'

def getRAM():
#get RAM as list,list[7],[8],[9]:total,used,free
RAM = os.popen('free').read().split()[7:10]
#convert kb in Mb for readablility
RAM0 = float(RAM[0])/1024
print 'RAM Total is %.1f MB' %RAM0
RAM1 = float(RAM[1])/1024
percent = RAM1/RAM0*100
print 'RAM Used is %.1f MB, %.2f' %(RAM1,percent) +'%'
RAM2 = float(RAM[2])/1024
print 'RAM Free is %.1f MB' %RAM2

def getDisk():
#get Disk information,DISK[8],[9],[10],[11]:Size, Used. free, Used %
DISK = os.popen('df -h /').read().split()[8:12]
print 'Disk total space is %s ' %DISK[0]
print 'Disk Used space is %s ' %DISK[1] +'and is %s' %DISK[3]
print 'Disk Free space is %s ' %DISK[2]

while True:
print '\n-------------SysInfo-----------------\n'
getCPUtemp()
getCPUusage()
getRAM()
getDisk()
print '\n-------------------------------------\n'
time.sleep(5)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 树莓派