树莓派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  # 也就是在所有的摄氏度前面加一个空格,因为摄氏度为字符无法获得数据格式
  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
树莓派4B使用VNC可以通过以下步骤进行设置和连接: 1. 在树莓派上启用VNC服务器。你可以通过在树莓派终端中运行以下命令来启用VNC服务器: ``` sudo raspi-config ``` 在菜单中选择"Interfacing Options",然后选择"VNC"并启用。 2. 在Windows上下载并安装VNC Viewer。 3. 打开VNC Viewer,在"VNC Server"字段中输入树莓派的IP地址,格式为IP地址:5900。例如,如果树莓派的IP地址为192.168.1.77,则应在"VNC Server"字段中输入192.168.1.77:5900。 4. 在"Name"字段中为连接起一个名字。 5. 点击"OK",然后输入设置的VNC密码。 6. 这样就能实现VNC远程操控树莓派,你可以在Windows端的VNC Viewer上查看并控制树莓派。 <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [树莓派4B上手教程 3.VNC远程桌面](https://blog.csdn.net/qq_40505381/article/details/126414236)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [树莓派Raspberry Pi 4B 安装VNC远程桌面服务](https://blog.csdn.net/luhengs/article/details/111881314)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值