打造自己的树莓派监控系统2--内存监控

代码编写

树莓派的内存使用情况可以使用如下命令查看:

free -m

结果如下:

              total        used        free      shared  buff/cache   available
Mem:            927         353          32          48         540         470
Swap:             0           0           0

而’free -m’命令是通过查看/proc/meminfo文件获得信息的:

cat /proc/meminfo

使用如下命令查看可用内存:

cat /proc/meminfo | grep MemAvailable

然后开始写代码:
获取内存:

def get_mem():
    try:
        MemAvailable = os.popen(
            "cat /proc/meminfo | grep MemAvailable |awk  '{print $2 / 1024}'").readline()
        MemAvailable = float(MemAvailable)
        return MemAvailable
    except Exception as e:
        print(e)

数据存放在数据库:

def create():
    # 创建数据库
    global conn
    conn = sqlite3.connect('data.db')
    conn.execute("""
                create table if not exists mem(
                id INTEGER PRIMARY KEY ,
                mem DOUBLE DEFAULT NULL,
                time INTEGER DEFAULT NULL)""")
    conn.commit()
def save(mem):
    # 将数据保存至本地
    global conn
    command1 = "insert into mem \
             (mem,time) values (?,?);"
    try:
        temp = (mem, int(round(time.time() * 1000)))
        conn.execute(command1, temp)
    except Exception as e:
        print(e)
        print("insert error!")
        conn.rollback()
    conn.commit()

最后是画图:

def mem():
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    global conn
    connect()
    mem,MemTotal = mem_get()
    ID = len(mem)
    past = datetime.datetime.now()-datetime.timedelta(minutes=ID)
    x = [past+datetime.timedelta(minutes=i)
         for i in range(ID)]
    plt.title("time and memory usage", fontsize=25)
    plt.xlabel("time", fontsize=15)
    plt.ylabel("memory usage", fontsize=15)
    plt.plot(x, mem)
    plt.ylim(0,MemTotal)
    plt.gcf().autofmt_xdate()
    plt.savefig('static/mem.jpg')

运行

此项目的GitHub地址:zhang0peter/raspberry-pi-monitor: 树莓派系统监控
运行如下命令:

git clone https://github.com/zhang0peter/raspberry-pi-monitor.git
cd raspberry-pi-monitor/
screen -S raspberry-pi-monitor
bash main.sh

然后在浏览器中打开http://127.0.0.1:4000/mem即可看到树莓派内存使用情况-时间图:

猜你喜欢

转载自blog.csdn.net/zhangpeterx/article/details/84288281