Saturday, March 28, 2015

Python display memory usage on Raspberry Pi/Linux

Linux command free display amount of free and used memory in the system. This example run the command "free -h" using Python, to display memory usage. It work on Raspberry Pi and also other Linux.



#Linux command free - Display amount of free and used memory in the system
# Example:
#pi@raspberrypi ~ $ free -h
#             total       used       free     shared    buffers     cached
#Mem:          863M       272M       591M         0B        19M       174M
#-/+ buffers/cache:        77M       785M
#Swap:          99M         0B        99M
#
# This sample run "free -h" in Python and get the result 
import os 

def getFreeDescription():
    free = os.popen("free -h")
    i = 0
    while True:
        i = i + 1
        line = free.readline()
        if i==1:
            return(line.split()[0:7])
                                 
def getFree():
    free = os.popen("free -h")
    i = 0
    while True:
        i = i + 1
        line = free.readline()
        if i==2:
            return(line.split()[0:7])

# Disk information
description = getFreeDescription()
mem = getFree()

print(description)
print(mem)
print(description[0] + " : " + mem[1])
print(description[1] + " : " + mem[2])
print(description[2] + " : " + mem[3])
print(description[3] + " : " + mem[4])
print(description[4] + " : " + mem[5])
print(description[5] + " : " + mem[6])


Run on Raspberry Pi 2/Raspbian:

Run on Ubuntu Linux:

No comments: