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有一个工具包,可以将文字转换为语音,支持英文和中文,而 ...
随机推荐
- Protocol Buffers 在前端项目中的使用
前言: 公司后端使用的是go语言,想尝试用pb和前端进行交互,于是便有了这一次尝试,共计花了一星期时间,网上能查到的文档几乎都看了一遍,但大多都是教在node环境下如何使用,普通的js环境下很多讲述的 ...
- java Integer parseInt()
先来一段代码,代码很简单的,如下: public static void main(String[] args) { Integer a = Integer.parseInt("3" ...
- Bzoj4016/洛谷P2993 [FJOI2014] 最短路径树问题(最短路径问题+长链剖分/点分治)
题面 Bzoj 洛谷 题解 首先把最短路径树建出来(用\(Dijkstra\),没试过\(SPFA\)\(\leftarrow\)它死了),然后问题就变成了一个关于深度的问题,可以用长链剖分做,所以我 ...
- 2017广西邀请赛 Query on A Tree (可持续化字典树)
Query on A Tree 时间限制: 8 Sec 内存限制: 512 MB提交: 15 解决: 3[提交][状态][讨论版] 题目描述 Monkey A lives on a tree. H ...
- HDU 6057 Kanade's convolution(FWT)
[题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=6057 [题目大意] 有 C[k]=∑_(i&j=k)A[i^j]*B[i|j] 求 Ans ...
- mysql 创建存储过程及测试sql
--存储过程 CREATE PROCEDURE proc_batch_id( out batch_id bigint ) begin insert into generate_sync_batch ( ...
- mysql事务简单测试
Auth: jinDate: 20140507 一.事务控制默认情况下,MySQL是自动提交(autocommit)的,如果需要通过明确的commit和rollblack来提交和回滚事务,那么需要通过 ...
- Spring注解@Primary的意思
@Primary:在众多相同的Bean中,优先使用@Primary注解的Bean. 这个和@Qualifier有点区别,@Qualifier指的是使用哪个Bean进行注入. 参考: http://bl ...
- jQuery插件示例笔记
插件的种类 封装对象方法的插件 将对象方法封装起来,用于对通过选择器获取的jQuery对象进行操作. //注意,为了更好的兼容性开始前有个分号 ;(function($){ //此处将$作为匿名函数的 ...
- Log4j 日志级别
转自:http://michales003.iteye.com/blog/1160605 日志记录器(Logger)是日志处理的核心组件.log4j具有5种正常级别(Level).: 1.static ...