python写的树莓派实时监控温度,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


最终代码如下:

[python]  view plain  copy
  1. #!/usr/bin/env python  
  2. import os  
  3. import time  
  4.   
  5.   
  6. #show raspberry temperature,CPU,memory  
  7.   
  8.   
  9. def getCPUtemp():  
  10.     temp = os.popen('vcgencmd measure_temp').readline()  
  11.     tempfloat = float(temp.replace('temp=','').replace('\'C\n',''))  
  12.     print 'CPU Temperature is now %.1f Centigrade' %tempfloat  
  13.     if tempfloat > 60:  
  14.         print 'CPU Temperature is too high, pls cool it down'  
  15.           
  16.   
  17. def getCPUusage():  
  18.         #calculate CPU with two short time, time2 - time1  
  19.         time1 = os.popen('cat /proc/stat').readline().split()[1:5]  
  20.         time.sleep(0.2)  
  21.         time2 = os.popen('cat /proc/stat').readline().split()[1:5]  
  22.         deltaUsed = int(time2[0])-int(time1[0])+int(time2[2])-int(time1[2])  
  23.         deltaTotal = deltaUsed + int(time2[3])-int(time1[3])  
  24.         cpuUsage = float(deltaUsed)/float(deltaTotal)*100  
  25.     print 'CPU Usage is now %.1f' %cpuUsage +'%'  
  26.   
  27.   
  28. def getRAM():  
  29.     #get RAM as list,list[7],[8],[9]:total,used,free  
  30.     RAM = os.popen('free').read().split()[7:10]  
  31.     #convert kb in Mb for readablility  
  32.     RAM0 = float(RAM[0])/1024  
  33.     print 'RAM Total is %.1f MB' %RAM0  
  34.     RAM1 = float(RAM[1])/1024  
  35.     percent = RAM1/RAM0*100  
  36.     print 'RAM Used  is %.1f MB, %.2f' %(RAM1,percent) +'%'  
  37.     RAM2 = float(RAM[2])/1024  
  38.     print 'RAM Free  is %.1f MB' %RAM2  
  39.   
  40.   
  41. def getDisk():  
  42.     #get Disk information,DISK[8],[9],[10],[11]:Size, Used. free, Used %  
  43.     DISK = os.popen('df -h /').read().split()[8:12]  
  44.     print 'Disk total space is %s ' %DISK[0]  
  45.     print 'Disk Used  space is %s ' %DISK[1] +'and is %s' %DISK[3]  
  46.     print 'Disk Free  space is %s ' %DISK[2]  
  47.   
  48.   
  49.   
  50.   
  51. while True:  
  52.     print '\n-------------SysInfo-----------------\n'  
  53.     getCPUtemp()  
  54.     getCPUusage()  
  55.     getRAM()  
  56.     getDisk()  
  57.     print '\n-------------------------------------\n'  
  58.     time.sleep(5)  



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值