Python监控进程性能数据并画图保存为PDF文档
引言
利用psutil模块(https://pypi.python.org/pypi/psutil/),可以很方便的监控系统的CPU、内存、磁盘IO、网络带宽等性能參数,下面是否代码为监控某个特定程序的CPU资源消耗。打印监控数据,终于画图显示,而且保存为指定的 PDF
文档备份。
示范代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2015 By Thomas Hu. All rights reserved. @author : Thomas Hu (thomashtq#163.com)
@version: 1.0
@created: 2015-7-14
'''
import matplotlib.pyplot as plt
import psutil as ps
import os
import time
import random
import collections
import argparse class ProcessMonitor(object):
def __init__(self, key_name, fields, duration, interval):
self.key_name = key_name
self.fields = fields
self.duration = float(duration)
self.inveral = float(interval) self.CPU_COUNT = ps.cpu_count()
self.MEM_TOTAL = ps.virtual_memory().total / (1024 * 1024)
self.procinfo_dict = collections.defaultdict(dict) def _get_proc_info(self, pid):
try:
proc = ps.Process(pid)
name = proc.name()
# If not contains the key word, return None
if name.find(self.key_name) == -1:
return None
pinfo = {
"name": name,
"pid" : pid,
}
# If the field is correct, add it to the process information dictionary.
for field in self.fields:
if hasattr(proc, field):
if field == "cpu_percent":
pinfo[field] = getattr(proc, field)(interval = 0.1) / self.CPU_COUNT
elif field == "memory_percent":
pinfo[field] = getattr(proc, field)() * self.MEM_TOTAL / 100
else:
pinfo[field] = getattr(proc, field)()
if pid not in self.procinfo_dict:
self.procinfo_dict[pid] = collections.defaultdict(list)
self.procinfo_dict[pid]["name"] = name
for field in self.fields:
self.procinfo_dict[pid][field].append(pinfo.get(field, 0))
print(pinfo)
return pinfo
except:
pass
return None def monitor_processes(self):
start = time.time()
while time.time() - start < self.duration:
try:
pids = ps.pids()
for pid in pids:
self._get_proc_info(pid)
except KeyboardInterrupt:
print("Killed by user keyboard interrupted!")
return def _get_color(self):
color = "#"
for i in range(3):
a = hex(random.randint(0, 255))[2:]
if len(a) == 1:
a = "0" + a
color += a
return color.upper() def draw_figure(self, field, pdf):
# Draw each pid line
for pid in self.procinfo_dict:
x = range(len(self.procinfo_dict[pid][field]))
#print x, self.procinfo_dict[pid][field]
plt.plot(x, self.procinfo_dict[pid][field], label = "pid" + str(pid), color = self._get_color())
plt.xlabel(time.strftime("%Y-%m-%d %H:%M:%S"))
plt.ylabel(field.upper())
plt.title(field + " Figure")
plt.legend(loc = "upper left")
plt.grid(True)
plt.savefig(pdf, dpi = 200)
plt.show() def Main():
parser = argparse.ArgumentParser(description='Monitor process CPU and Memory.')
parser.add_argument("-k", dest='key', type=str, default="producer",
help='the key word of the processes to be monitored(default is "producer")')
parser.add_argument("-d", dest='duration', type=int, default=60,
help='duration of the monitor to run(unit: seconds, default is 60)')
parser.add_argument('-i', dest='interval', type=float, default=1.0,
help='interval of the sample(unit: seconds, default is 1.0)')
args = parser.parse_args()
fields = ["cpu_percent", "memory_percent"]
#print args.key, args.duration, args.interval
pm = ProcessMonitor(args.key, fields, args.duration, args.interval)
pm.monitor_processes()
pm.draw_figure("cpu_percent", "cpu.pdf")
pm.draw_figure("memory_percent", "mem.pdf") if __name__ == "__main__":
Main()
输出结果示范图
Python监控进程性能数据并画图保存为PDF文档的更多相关文章
- ABBYY FineReader 15 中保存和导出PDF文档的小细节
运用ABBYY FineReader OCR文字识别软件,用户能将各种格式的PDF文档保存为新的PDF文档.PDF/A格式文档,以及Microsoft Word.Excel.PPT等格式.在保存与导出 ...
- 使用Jyhon脚本和PMI模块监控WAS性能数据
使用Jyhon脚本和PMI模块监控WAS性能数据的优点有: 1.可以使用非交互的方式远程获取数据 2.不需要图形化模块支持 3.对各种was版本的兼容性较高 4.使用方便,官方自带 缺点也有很多: 1 ...
- Python进阶----进程间数据隔离, join阻塞等待, 进程属性, 僵尸进程和孤儿进程, 守护进程
Python进阶----进程间数据隔离, join阻塞等待, 进程属性, 僵尸进程和孤儿进程, 守护进程 一丶获取进程以及父进程的pid 含义: 进程在内存中开启多个,操作系统如何区分这些进程, ...
- Python处理Excel和PDF文档
一.使用Python操作Excel Python来操作Excel文档以及如何利用Python语言的函数和表达式操纵Excel文档中的数据. 虽然微软公司本身提供了一些函数,我们可以使用这些函数操作Ex ...
- 程序生成word与PDF文档的方法(python)
程序导出word文档的方法 将web/html内容导出为world文档,再java中有很多解决方案,比如使用Jacob.Apache POI.Java2Word.iText等各种方式,以及使用free ...
- python爬虫处理在线预览的pdf文档
引言 最近在爬一个网站,然后爬到详情页的时候发现,目标内容是用pdf在线预览的 比如如下网站: https://camelot-py.readthedocs.io/en/master/_static/ ...
- 将mat文件中的数据按要求保存到txt文档中(批处理)
之前有个老朋友,让帮忙将一个mat中的数据重新保存到txt中,由于数据比较多需要用到批处理,之前弄过很多次,但每次一到要用的时候总是忘记怎么写了,现在记录一下,免得后面老是需要上网搜.这里先说一个比较 ...
- python实用小技能分享,教你如何使用 Python 将 pdf 文档进行 加密 解密
上次说了怎么将word转换为pdf格式 及 实现批量将word转换为pdf格式(点击这里),这次我又get到一个新技能–使用 Python 将 pdf 文档进行 加密 解密,哈哈哈 希望帮到更多人! ...
- 利用Python将PDF文档转为MP3音频
1. 转语音工具 微信读书有一个功能,可以将书里的文字转换为音频,而且声音优化的不错,比传统的机械朗读听起来舒服很多. 记得之前看到过Python有一个工具包,可以将文字转换为语音,支持英文和中文,而 ...
随机推荐
- 【我要学python】open函数的简单用法
open函数 1,使用方法:open('文件路径', '模式',编码方式). 2,最好使用with open as: 省去每一次都需要close()的环节 3,模式介绍: ①w 可写(如果存在,会覆盖 ...
- Python开发基础-Day12模块1
time模块 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的时间字符串: (1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月 ...
- JZYZOJ1502 [haoi2008]下落的圆盘 计算几何 贪心
http://172.20.6.3/Problem_Show.asp?id=1502这种题用了快一天才写出来也是真的辣鸡.主要思路就是计算一下被挡住的弧度然后对弧度进行贪心.最开始比较困扰的是求弧度值 ...
- [Codeforces 1053C] Putting Boxes Together
Link: Codeforces 1053C 传送门 Solution: 先推出一个结论: 最后必有一个点不动且其为权值上最中间的一个点 证明用反证证出如果不在中间的点必有一段能用代价少的替代多的 这 ...
- poj 3225 Help with Intervals(线段树,区间更新)
Help with Intervals Time Limit: 6000MS Memory Limit: 131072K Total Submissions: 12474 Accepted: ...
- CodeForces - 1000E We Need More Bosses
题面在这里! 依然一眼题,求出割边之后把图缩成一棵树,然后直接求最长链就行了2333 #include<bits/stdc++.h> #define ll long long using ...
- [Agc008F]Black Radius
[AGC008F] Black Radius Description 给你一棵有N个节点的树,节点编号为1到N,所有边的长度都为1 "全"对某些节点情有独钟,这些他喜欢的节点的信息 ...
- 【二分】Jessica's Reading Problem
[POJ3320]Jessica's Reading Problem Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 1309 ...
- Redis源码解析之ziplist
Ziplist是用字符串来实现的双向链表,对于容量较小的键值对,为其创建一个结构复杂的哈希表太浪费内存,所以redis 创建了ziplist来存放这些键值对,这可以减少存放节点指针的空间,因此它被用来 ...
- mysql常见故障问题汇总
Auth: JinDate: 20140414 UpdateDate: 继续更新 导库字符集的问题http://www.cnblogs.com/diege/p/3640618.htmlmysql-pr ...