欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實(shí)現(xiàn)內(nèi)存監(jiān)控系統(tǒng)

 更新時(shí)間:2021年03月07日 09:19:10   作者:Sancy森  
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)內(nèi)存監(jiān)控系統(tǒng),通過系統(tǒng)命令或操作系統(tǒng)文件獲取到內(nèi)存信息,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了python實(shí)現(xiàn)內(nèi)存監(jiān)控系統(tǒng)的具體代碼,供大家參考,具體內(nèi)容如下

思路:通過系統(tǒng)命令或操作系統(tǒng)文件獲取到內(nèi)存信息(linux 內(nèi)存信息存在/proc/meminfo文件中,mac os 通過命令vm_stat命令可以查看)

并將獲取到信息保存到數(shù)據(jù)庫中,通過web將數(shù)據(jù)實(shí)時(shí)的展示出來.(獲取數(shù)據(jù)—展示數(shù)據(jù))

1、后臺數(shù)據(jù)采集(獲取數(shù)據(jù))

import subprocess
import re
import MySQLdb as mysql
import time
import socket

#獲取mysql數(shù)據(jù)游標(biāo),通過游標(biāo)操作數(shù)據(jù)庫
db = mysql.connect(user="root", passwd="123456",host="localhost", db="EBANK", charset="utf8")
db.autocommit(True)
cur = db.cursor()

"""
 Mac系統(tǒng)各應(yīng)用程序占內(nèi)存信息
"""
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內(nèi)存活動(dòng)信息
"""
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

"""
 執(zhí)行更新數(shù)據(jù)庫中內(nèi)存信息,供web展示內(nèi)存的實(shí)時(shí)數(shù)據(jù)
"""
erval = 0
def execute():
 '''更新內(nèi)存活動(dòng)信息'''
 global erval
 try:
 ip = socket.gethostbyname(socket.gethostname()) #獲取本機(jī)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 '執(zhí)行數(shù)據(jù)清理.',del_sql
  cur.execute(del_sql)
  erval = 0

 except Exception , message :
 print '獲取內(nèi)存信息異常:',message
 #pass
 finally:
 pass


 '''更新'''
 #TODO
 #rssTotal = processesUseMeminfo()

#死循環(huán)不停的讀取內(nèi)存,每一秒鐘插入一條新的內(nèi)存信息
while True:
 time.sleep(1)
 execute()
 print 'none.'

獲取到數(shù)據(jù)保存到MySQL數(shù)據(jù)中,新建表:

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應(yīng)用框架,通過highstock實(shí)時(shí)展示折線圖數(shù)據(jù)

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():
 '''第一次查詢?nèi)繑?shù)據(jù),后面只查詢增量數(shù)據(jù)'''
 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)

新建一個(gè)monitor.html

<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>內(nèi)存監(jiān)控</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" style="min-width:400px;height:400px"></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,實(shí)時(shí)獲取內(nèi)存信息
   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.

運(yùn)行后臺數(shù)據(jù)采集,運(yùn)行前臺web,通過http://localhost:8888/ 實(shí)時(shí)監(jiān)控內(nèi)存的活動(dòng)情況。

效果圖

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論