根据进程名监控其运行过程中的内存占用情况
import os, re
import time
import string
import xlrd
import xlwt
from xlutils.copy import copy
def countProcessMemoey(processName):
pattern = re.compile(r'([^\s]+)\s+(\d+)\s.*\s([^\s]+\sK)')
cmd = 'tasklist /fi "imagename eq ' + processName + '"' + ' | findstr.exe ' + '"'+ processName + '"'
result = os.popen(cmd).read()
resultList = result.split("\n")
for srcLine in resultList:
srcLine = "".join(srcLine.split('\n'))
if len(srcLine) == 0:
break
m = pattern.search(srcLine)
if m == None:
continue
if str(os.getpid()) == m.group(2):
continue
ori_mem = m.group(3).replace(',','')
ori_mem = ori_mem.replace(' K','')
ori_mem = ori_mem.replace(r'\sK','')
memEach = int(ori_mem)
print ('ProcessName:'+ m.group(1) + '\tPID:' + m.group(2) + '\tmemory size:%.2f'% (memEach * 1.0 /1024), 'M')
cpu = '%.2f'% (memEach * 1.0 /1024) +'M'
value = [time.ctime(), cpu]
rb = xlrd.open_workbook(r'./monitor.xls', formatting_info=True)
wb = copy(rb)
writeSheet = wb.get_sheet(0)
writeSheet.write(x, y, value[0])
writeSheet.write(x, y+1, value[1])
wb.save(r'./monitor.xls')
print("*" * 58)
if __name__ == '__main__':
book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')
book.save('monitor_python.xls')
ProcessName = 'python2.exe'
x = 0
y = 0
while True:
countProcessMemoey(ProcessName)
x += 1
time.sleep(5)
import sys
import time
import psutil
def monitor(pid):
p = psutil.Process(pid)
interval = 3
with open("process_monitor_" + p.name() + '_' + str(pid) + ".csv", "a+") as f:
f.write("time,cpu%,mem%\n")
while True:
current_time = time.strftime('%Y%m%d-%H%M%S',time.localtime(time.time()))
cpu_percent = p.cpu_percent()
mem_percent = p.memory_percent()
line = current_time + ',' + str(cpu_percent) + ',' + str(mem_percent)
print (line)
f.write(line + "\n")
time.sleep(interval)
if __name__ == '__main__':
pid = 22000
monitor(pid)
'''监控系统cpu与内存情况'''
import psutil
import datetime
from xlrd import open_workbook
from xlutils.copy import copy
import time
def cpu():
cpu = psutil.cpu_count(False)
cpu_per = int(psutil.cpu_percent(1))
return cpu_per
def mem():
mem = psutil.virtual_memory()
mem_total = int(mem[0]/1024/1024)
mem_used = int(mem[3]/1024/1024)
mem_per = int(mem[2])
mem_info = {
'mem_total': mem_total,
'mem_used': mem_used,
'mem_per': mem_per,
}
return mem_info
def disk():
c_per = int(psutil.disk_usage('C:')[3])
d_per = int(psutil.disk_usage('d:')[3])
disk_info = {
'c_per': c_per,
'd_per': d_per,
}
return disk_info
def network():
network = psutil.net_io_counters()
network_sent = int(psutil.net_io_counters()[0] / 8 / 1024)
network_recv = int(psutil.net_io_counters()[1]/8/1024)
network_info = {
'network_sent': network_sent,
'network_recv': network_recv
}
return network_info
def all_msg():
msg = []
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
msg.append(now_time)
cpu_info = cpu()
msg.append(cpu_info)
mem_info = mem()
msg.append(mem_info['mem_per'])
disk_info = disk()
msg.append(disk_info['c_per'])
msg.append(disk_info['d_per'])
network_info = network()
msg.append(network_info['network_sent'])
msg.append(network_info['network_recv'])
return msg
def write_xls(lis, filename, row):
rb = open_workbook(filename, formatting_info=True)
wb = copy(rb)
ws = wb.get_sheet(0)
for i in range(0, len(lis)):
ws.write(row, i, lis[i])
wb.save(filename)
def main():
cnt_times = 1
row = 0;
while(1):
msg = all_msg()
print(msg)
write_xls(msg, "./cs_monitor.xls", row)
cnt_times += 1
time.sleep(10)
row+=1
main()
"""
# 发邮件进行实时报告计算机的状态
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from email.header import Header
def send_email(info):
sender = '***@qq.com'
recevier = '***@qq.com'
subject = 'Warning'
username = '***@qq.com'
password = '***' # 相应的密码
msg = MIMEText(info, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = sender
msg['To'] = recevier
smtp = smtplib.SMTP()
smtp.connect('smtp.qq.com')
smtp.login(username, password)
smtp.sendmail(sender, recevier, msg.as_string())
smtp.quit()
# 主函数调用,调用其他信息
def main():
cpu_info = cpu()
mem_info = mem()
disk_info = disk()
network_info = network()
info = '''
监控信息
=========================
cpu使用率: : %s,
=========================
内存总大小(MB) : %s,
内存使用大小(MB) : %s,
内存使用率 : %s,
=========================
C盘使用率: %s,
D盘使用率: %s,
E盘使用率: %s,
=========================
网络流量接收的量(MB) : %s,
网络流量发送的量(MB): %s,
''' % (cpu_info,
mem_info['mem_total'], mem_info['mem_used'], mem_info['mem_per'],
disk_info['c_per'], disk_info['d_per'], disk_info['e_per'],
network_info['network_sent'], network_info['network_recv'])
send_email(info)
main()
"""
|