树莓派4B监控CPU占用率、内存使用率、磁盘使用量以及CPU温度

树莓派作为一个小型电脑,可以采用指令、程序语言来获取其资源状态等信息

树莓派可以作为一个小型电脑,但是它不能像windows一样使用任务管理器查看当前资源占用情况

一、使用指令查看当前资源状态

  1. 使用top指令
    可以获取当前Cpu使用状态、RAM使用率等信息,但是只能查看,无法长时间运行时保存下来
    在这里插入图片描述

  2. 使用free指令
    可以获得Mem信息,但是是以byte为单位,需要转换单位
    在这里插入图片描述

  3. 使用df指令
    可以获得文件系统占用的详情
    在这里插入图片描述

二、用Python语言获取资源状态并存储为txt文件

import os
import time
import logging

# Return CPU temperature as a character string                                     
def  getCPUtemperature():
     res  = os.popen( 'vcgencmd measure_temp' ).readline()
     return (res.replace( "temp=" ," ").replace(" 'C\t "," "))

# Return RAM information (unit=kb) in a list                                      
# Index 0: total RAM                                                              
# Index 1: used RAM                                                                
# Index 2: free RAM                                                                
def  getRAMinfo():
     p  = os.popen( 'free' )
     i  = 0
     while  1 :
         i  = i  + 1
         line  = p.readline()
         if  i == 2 :
             return (line.split()[ 1 : 4 ])
 
# Return % of CPU used by user as a character string                               
def  getCPUuse():
     return ( str (os.popen( "top -n1 | awk '/Cpu\(s\):/ {print $2}'" ).readline().strip()))
 
# Return information about disk space as a list (unit included)                    
# Index 0: total disk space                                                        
# Index 1: used disk space                                                        
# Index 2: remaining disk space                                                    
# Index 3: percentage of disk used                                                 
def  getDiskSpace():
     p = os.popen( "df -h /" )
     i = 0
     while 1 :
         i  = i  + 1
         line  = p.readline()
         if i == 2 :
             return (line.split()[ 1 : 5 ])

def get_info():
     
     # CPU informatiom
     CPU_temp  = getCPUtemperature()
     CPU_usage  = getCPUuse()
     
     # RAM information
     # Output is in kb, here I convert it in Mb for readability
     RAM_stats  = getRAMinfo()
     RAM_total  = round ( int (RAM_stats[ 0 ])  / 1024 , 1 )
     RAM_used  = round ( int (RAM_stats[ 1 ])  / 1024 , 1 )
     RAM_free  = round ( int (RAM_stats[ 2 ])  / 1024 , 1 )
     
     # Disk information
     DISK_stats  = getDiskSpace()
     DISK_total  = DISK_stats[0]
     DISK_used  = DISK_stats[1]
     DISK_left = DISK_stats[2]
     DISK_perc  = DISK_stats[3]
     
     logging.info(
          "Local Time {timenow} \n"
          "CPU Temperature ={CPU_temp}"
          "CPU Use = {CPU_usage} %\n\n"
          "RAM Total = {RAM_total} MB\n"
          "RAM Used = {RAM_used} MB\n"
          "RAM Free = {RAM_free} MB\n\n"
          "DISK Total Space = {DISK_total}B\n"
          "DISK Used Space = {DISK_used}B\n"
          "DISK Left Space = {DISK_left}B\n"
          "DISK Used Percentage = {DISK_perc}\n"
          "".format(
               timenow = time.asctime(time.localtime(time.time())),
               CPU_temp = CPU_temp,
               CPU_usage = CPU_usage,
               RAM_total = str(RAM_total),
               RAM_used = str(RAM_used),
               RAM_free = str(RAM_free),
               DISK_total = str(DISK_total),
               DISK_used = str(DISK_used),
               DISK_left = str(DISK_left),
               DISK_perc = str(DISK_perc),
               )
     )

if __name__  == '__main__':
     # get info
     logger_file = os.path.join('log_source_info.txt')
     handlers = [logging.FileHandler(logger_file, mode='w'),
                logging.StreamHandler()]
     logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] '
                           '- %(levelname)s: %(message)s',
                           level=logging.INFO,
                           handlers=handlers)
     # while(1):
     while(True):
          get_info()
          time.sleep(10) # Time interval for obtaining resources

获取的文件形式如下:

在这里插入图片描述

三、获得了各种资源状态记录的txt文件,但是统计起来十分麻烦,特别是对于长时间记录的情况。可使用Python对保存的txt文件进行操作,将数据保存到csv,以CPU use和RAM use为例:

import numpy as np
addr = "log_source_info"

len_txt = len(open(addr + ".txt",'r').readlines())
len_data = int(len_txt / 13)

data = np.zeros([len_txt, 1]).astype(object)
data_i = 0 

with open(addr + addr_num + ".txt", "r") as f:
    for line in f.readlines():
        line = line.strip('\n')
        data[data_i] = line
        data_i += 1
# print(data)
# CPU_Temp = np.zeros([len_data, 1]).astype(object)
CPU_Use = np.zeros([len_data, 1]).astype(object)
RAM_Total = 2976.6
RAM_Used = np.zeros([len_data, 1]).astype(object)
# CPU_Temp_cont = 0
CPU_Use_cont = 0
RAM_Used_cont = 0

cont = 0
for data_t in data:
    # print(data_t)
    temp = data_t[0].split(" ")
    # if cont == 1 :
        # CPU_Temp[CPU_Temp_cont] = float(temp[3])
        # CPU_Temp_cont += 1
    if cont == 2:
        # find some data miss
        if temp[3] == '%':
            CPU_Use[CPU_Use_cont] = 0
        else :
            # print(temp[3])
            CPU_Use[CPU_Use_cont] = float(temp[3])
        CPU_Use_cont += 1
    elif cont == 5:
        RAM_Used[RAM_Used_cont] = float(temp[3]) / RAM_Total
        RAM_Used_cont += 1
    # print(data)
    cont += 1
    cont %= 13
with open(addr + addr_num + ".csv", "w") as fw :
    # fw.write("CPU_Temp" + "," + "CPU_Use" + "," + "RAM_Used" + "," + "\n")
    fw.write("CPU_Use" + "," + "RAM_Used" + "," + "\n")
    for i in range(len_data):
        # fw.write(str(CPU_Temp[i,0]) + "," + str(CPU_Use[i,0]) + "," + str(RAM_Used[i,0]) + "\n")
        fw.write(str(CPU_Use[i,0]) + "," + str(RAM_Used[i,0]) + "\n")

注意!!! 如果需要对CPU温度进行获取到csv文件,需要对txt文件进行处理,使用查找->替换,将

'C

替换为:

 'C  # 也就是在所有的摄氏度前面加一个空格,因为摄氏度为字符无法获得数据格式

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
旺仔牛奶opo
旺仔牛奶opo

15 篇文章

作家榜 »

  1. Panda-admin 37 文章
  2. 解弘艺 17 文章
  3. 高曾谊 16 文章
  4. 旺仔牛奶opo 15 文章
  5. 胡中天 14 文章
  6. LH 14 文章
  7. 罗柏荣 13 文章
  8. 林晨 12 文章