今天介紹將記憶體使用情況匯製圖形的Python程式.
程式碼如下:
#!/usr/bin/env python
# ---------------------------
# Python RRDTool
# Memory Data
# Create Image from rrd file
# ---------------------------
import rrdtool
import datetime
def mem_graph(rrdfile, period):
timenow = datetime.datetime.now()
disptime = datetime.datetime.strftime(timenow, '%Y-%m-d %H-%M-%S')
title = 'Memory_Usage_' + period
filename = title + '.png'
# -------------------
mfree = 'DEF:mfree=%s:mfree:AVERAGE' % rrdfile
mbuff = 'DEF:mbuff=%s:mbuff:AVERAGE' % rrdfile
mcach = 'DEF:mcach=%s:mcach:AVERAGE' % rrdfile
mtotl = 'DEF:mtotl=%s:mtotl:AVERAGE' % rrdfile
mused = 'CDEF:mused=mtotl,mfree,-'
# -------------------
if period == 'yesterday':
start = 'end-1d'
end = '00:00'
if period == 'today':
start = '00:00'
end = '23:59'
if period == '2h':
start = '-2h'
end = 'now'
rrdtool.graph(
filename,
'--start', start,
'--end', end,
'--title', title,
'-a', 'PNG',
'-W', 'Hitomitanaka for ITHelp',
'--slope-mode',
'--vertical-label=K Bytes',
'--rigid',
'--lower-limit', '0',
'--width', '500',
'--height', '150',
'--x-grid', 'HOUR:1:HOUR:2:HOUR:2:0:%H',
'--alt-y-grid',
'--color', 'BACK#000000',
'--color', 'CANVAS#000000',
'--color', 'FONT#FFF978',
'--font=LEGEND:7',
'--font', 'TITLE:8:',
'--font', 'UNIT:7:',
'--font', 'WATERMARK:9',
# ---------------------------------
mcach,
mfree,
mbuff,
mtotl,
mused,
#----------------------------------
'AREA:mused#4444EE:Used',
'GPRINT:mused:LAST: Current\\: %.01lf',
'GPRINT:mused:AVERAGE: Average\\: %.01lf',
'GPRINT:mused:MIN: Min\\: %.01lf',
'GPRINT:mused:MAX: Max\\: %.01lf\\n',
'AREA:mcach#EEEE00:Cached',
'GPRINT:mcach:LAST:Current\\: %.01lf',
'GPRINT:mcach:AVERAGE: Average\\: %.01lf',
'GPRINT:mcach:MIN: Min\\: %.01lf',
'GPRINT:mcach:MAX: Max\\: %.01lf\\n',
'AREA:mbuff#EE4444:Buffer',
'GPRINT:mbuff:LAST:Current\\: %.01lf',
'GPRINT:mbuff:AVERAGE: Average\\: %.01lf',
'GPRINT:mbuff:MIN: Min\\: %.01lf',
'GPRINT:mbuff:MAX: Max\\: %.01lf\\n',
'COMMENT:\t\t\t\tUpdate Time %s' % disptime)
#
if __name__ == '__main__':
mem_graph('memory.rrd', 'today')
mem_graph('memory.rrd', 'yesterday')
圖形如下: