您好,登錄后才能下訂單哦!
這篇文章主要介紹python如何實現內存監控系統,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
具體內容如下
思路:通過系統命令或操作系統文件獲取到內存信息(linux 內存信息存在/proc/meminfo文件中,mac os 通過命令vm_stat命令可以查看)
并將獲取到信息保存到數據庫中,通過web將數據實時的展示出來.(獲取數據—展示數據)
1、后臺數據采集(獲取數據)
import subprocess import re import MySQLdb as mysql import time import socket #獲取mysql數據游標,通過游標操作數據庫 db = mysql.connect(user="root", passwd="123456",host="localhost", db="EBANK", charset="utf8") db.autocommit(True) cur = db.cursor() """ Mac系統各應用程序占內存信息 """ def processesUseMeminfo(): ps = subprocess.Popen(['ps', '-caxm', '-orss,comm'], stdout=subprocess.PIPE).communicate()[0] processLines = ps.split('\n') print processLines sep = re.compile('[\s]+') rssTotal = 0 # kB for row in range(1,len(processLines)): rowText = processLines[row].strip() rowElements = sep.split(rowText) try: rss = float(rowElements[0]) * 1024 except: rss = 0 # ignore... rssTotal += rss return rssTotal """ Mac內存活動信息 """ def processVM(): vm = subprocess.Popen(['vm_stat'], stdout=subprocess.PIPE).communicate()[0] vmLines = vm.split('\n') sep = re.compile(':[\s]+') vmStats = {} for row in range(1,len(vmLines)-2): rowText = vmLines[row].strip() rowElements = sep.split(rowText) vmStats[(rowElements[0])] = int(rowElements[1].strip('\.'))/1024 return vmStats """ 執行更新數據庫中內存信息,供web展示內存的實時數據 """ erval = 0 def execute(): '''更新內存活動信息''' global erval try: ip = socket.gethostbyname(socket.gethostname()) #獲取本機ip #ip = '10.21.8.10' vmStats = processVM() wired = vmStats['Pages wired down'] active = vmStats['Pages active'] free = vmStats['Pages free'] inactive = vmStats['Pages inactive'] t = int(time.time()) sql = "insert into stat(host,mem_free,mem_usage,mem_total,load_avg,time) VALUES ('%s','%d','%d','%d','%d','%d')"\ %(ip,wired,active,free,inactive,t) print sql cur.execute(sql) erval += 1 if erval > 50: del_sql = "delete from stat where time < %d "%t print '執行數據清理.',del_sql cur.execute(del_sql) erval = 0 except Exception , message : print '獲取內存信息異常:',message #pass finally: pass '''更新''' #TODO #rssTotal = processesUseMeminfo() #死循環不停的讀取內存,每一秒鐘插入一條新的內存信息 while True: time.sleep(1) execute() print 'none.'
獲取到數據保存到MySQL數據中,新建表:
CREATE TABLE `stat` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `host` varchar(256) DEFAULT NULL, `mem_free` int(11) DEFAULT NULL, `mem_usage` int(11) DEFAULT NULL, `mem_total` int(11) DEFAULT NULL, `load_avg` varchar(128) DEFAULT NULL, `time` bigint(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `host` (`host`(255)) ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
2、前臺web采用flask應用框架,通過highstock實時展示折線圖數據
from flask import Flask, request, render_template import json import MySQLdb as mysql app = Flask(__name__) db = mysql.connect(user="root", passwd="123456",host="localhost", db="EBANK", charset="utf8") db.autocommit(True) cur = db.cursor() @app.route("/") def index(): return render_template("monitor.html") tmp_time = 0 @app.route("/data") def getdata(): '''第一次查詢全量數據,后面只查詢增量數據''' global tmp_time if tmp_time > 0 : sql = "select time,mem_free from stat where time >%s" %(tmp_time) else: sql = "select time,mem_free from stat" cur.execute(sql) datas = [] for i in cur.fetchall(): datas.append([i[0], i[1]]) if len(datas) > 0 : tmp_time = datas[-1][0] return json.dumps(datas) if __name__ == "__main__": app.run(host='0.0.0.0',port=8888,debug=True)
新建一個monitor.html
<html lang="en"> <head> <meta charset="UTF-8"> <title>內存監控</title> <script src="http://cdn.hcharts.cn/jquery/jquery-1.8.3.min.js"></script> <script src="http://cdn.hcharts.cn/highstock/highstock.js"></script> <script src="http://cdn.hcharts.cn/highcharts/modules/exporting.js"></script> </head> <body> <div id="container" ></div> </body> <script type="text/javascript"> $(function () { $.getJSON('/data', function (data) { // Create the chart $('#container').highcharts('StockChart', { chart: { events: { load: function () { var chart = $('#container').highcharts(); var series = chart.series[0]; //隔1秒,請求一次/data,實時獲取內存信息 setInterval(function () { $.getJSON("/data", function (res) { $.each(res, function (i, v) { series.addPoint(v); }); }); }, 1000); } } }, rangeSelector : { selected : 1 }, title : { text : 'AAPL Stock Price' }, series : [{ name : 'AAPL', data : data, tooltip: { valueDecimals: 2 } }] }); }); }); </script> </html>
done.
運行后臺數據采集,運行前臺web,通過http://localhost:8888/ 實時監控內存的活動情況。
效果圖
以上是“python如何實現內存監控系統”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。