1.前提建立数据库和表格式python

[root@python ~]# mysql -uroot -pcentosmysql

mysql> create database memory;sql

mysql> use memory;数据库

mysql> create table memory (memory int,time varchar(50));centos


2.编写每睡眠一秒就将系统use_mem内存写入数据库ide

[root@python ~]# cat mem.py spa

#!/usr/bin/env python对象

#-*- coding: UTF-8 -*-blog


import time #导入时间模块内存

import MySQLdb as mysql  #导入MySQLdb模块


db=mysql.connect(user='root',passwd='centos',db='memory',host='localhost')  #链接数据库


cursor=db.cursor() #建立游标对象


def getMem():

f = open('/proc/meminfo')

total = int(f.readline().split()[1])

free = int(f.readline().split()[1])

buffer = int(f.readline().split()[1])

cache = int(f.readline().split()[1])

mem_used = total - free - buffer - cache

cur_time =time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))

sql = 'insert into memory (memory, time) value (%s,%s)'%(mem_used,cur_time)

cursor.execute(sql) #执行sql语句

print 'ok'


while True:

getMem()

time.sleep(1)   # sleep 1 second


3.执行脚本,查看数据库

捕获.PNG

捕获.PNG