I am currently working on an application to use my RPi to monitor what is happening in my flat (temperature, ...) but I also want to use this application to monitor how fine my RPi is going.
As it might be of interest for some of you I decided to share some code to monitor the CPU, RAM and disk of the RPi (I have a model B, 512 Mb, Raspbian and use python 2.7 + pygame for the interface).
First the functions that can allow you to retrieve CPU information (temperature + usage), RAM info (total, usage) and disk usage (total, usage). The comments generally explain quite well the functions that actually rely on Unix commands launched from Python.
Code: Select all
import os
# Return CPU temperature as a character string
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
return(res.replace("temp=","").replace("'C\n",""))
# 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])
If you want to call the function here are some examples:
Code: Select all
# 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]) / 1000,1)
RAM_used = round(int(RAM_stats[1]) / 1000,1)
RAM_free = round(int(RAM_stats[2]) / 1000,1)
# Disk information
DISK_stats = getDiskSpace()
DISK_total = DISK_stats[0]
DISK_free = DISK_stats[1]
DISK_perc = DISK_stats[3]
I used these chunks of codes for my interface and, so far, it works nicely and gives this kind of results: see image. The design still sucks (icons are not very explicit) but I will work on this later.

If you have any questions or want to share your tips to monitor your RPi activity using Python feel free to use this topic. By the way, the code presented here is of course free to be used. I do not guarantee it will work on every RPi but I hope so. =)
Final comment: I didn't know where to post this topic. Please move it if you think it is better suited in an other forum.
Philippe.