python学习-获取计算机内存占有率和CPU占有率并绘制折线图

项目目标:

1、获取计算机内存占有率和CPU占有率
2、将数据存储到excel表格
3、提取excel数据并绘制折线图

实现方式

1、利用psutil,os,time模块获取数据

#获取当前运行的pid
p1=psutil.Process(os.getpid())

#获取数据
 b = psutil.cpu_percent(interval=1.0)  # cpu占用率
 a = psutil.virtual_memory().percent  # 内存占用率
nowtime = time.strftime("%H:%M:%S", time.localtime())

2、利用xlwt模块将数据写入excel表格

#创建excel表格和sheet
    myxls = xlwt.Workbook()
    sheet1 = myxls.add_sheet(u'CPU')
 #写入标题
    sheet1.write(0, 0, '当前时间')
    sheet1.write(0, 1, 'cpu占用率')
    sheet1.write(0, 2, '内存占用率')
  #写入数据
      i=1
    for i in range(1,10):
        b = psutil.cpu_percent(interval=1.0)  # cpu占用率
        a = psutil.virtual_memory().percent  # 内存占用率
        nowtime = time.strftime("%H:%M:%S", time.localtime())
        sheet1.write(i,0,nowtime)
        print(nowtime)
        sheet1.write(i,1,b)
        print(b)
        sheet1.write(i,2,a)
        myxls.save('CPU.xls')
        i+=1
    

3、利用xlrd模块获取excel中数据

# 获取折线图需要绘制的数据信息;
    data=xlrd.open_workbook("CPU.xls")
    table=data.sheets()[0]
    print(table.ncols)
    row1data = table.row_values(0)
    print(row1data)  # ['列1', '列2', '列3', '列4']

    x = []
    y1 = []
    y2 = []
    for i in range(1, table.nrows):
        print(table.row_values(i))
        x.append(table.row_values(i)[0])
        y1.append(table.row_values(i)[1])
        y2.append(table.row_values(i)[2])

4、利用pyecharts模块绘制折线图

# 实例化Line类为line对象, 并添加x和y对应的点;
        line = (
         Line()
         .add_xaxis(x)
         .add_yaxis("Cpu占有率散点图", y1)
         .add_yaxis("内存占有率散点图", y2)
        # .set_global_opts(title_opts=opts.TitleOpts(title="Cpu占有率散点图"))
     )
# 将折线图信息保存到文件中;
        line.render("show.html")

所遇问题

打开excel时遇见问题

错误: Python读取文件时出现UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0x80 in position xx: 解决方案
原因:使用open函数可能会遇见问题
方法1:data= open(‘order.log’,‘r’, encoding=‘UTF-8’)
方法2:改成xlrd打开,data=xlrd.open_workbook(“CPU.xls”)

绘制图像时

错误:ImportError: cannot import name ‘Line’ from ‘pyecharts’
原因:新版本要使用新的格式
改成:from pyecharts.charts import Line

完整代码

import psutil
import os
import xlwt
import xlrd
import time
from pyecharts.charts import Line


#获取当前运行的pid
p1=psutil.Process(os.getpid())

while True:


    myxls = xlwt.Workbook()
    sheet1 = myxls.add_sheet(u'CPU')
    sheet1.write(0, 0, '当前时间')
    sheet1.write(0, 1, 'cpu占用率')
    sheet1.write(0, 2, '内存占用率')

    i=1
    for i in range(1,10):
        b = psutil.cpu_percent(interval=1.0)  # cpu占用率
        a = psutil.virtual_memory().percent  # 内存占用率
        nowtime = time.strftime("%H:%M:%S", time.localtime())
        sheet1.write(i,0,nowtime)
        print(nowtime)
        sheet1.write(i,1,b)
        print(b)
        sheet1.write(i,2,a)
        myxls.save('CPU.xls')
        i+=1


# 获取折线图需要绘制的数据信息;
    data=xlrd.open_workbook("CPU.xls")
    table=data.sheets()[0]
    print(table.ncols)
    row1data = table.row_values(0)
    print(row1data)  # ['列1', '列2', '列3', '列4']

    x = []
    y1 = []
    y2 = []
    for i in range(1, table.nrows):
        print(table.row_values(i))
        x.append(table.row_values(i)[0])
        y1.append(table.row_values(i)[1])
        y2.append(table.row_values(i)[2])
# 实例化Line类为line对象, 并添加x和y对应的点;
        line = (
         Line()
         .add_xaxis(x)
         .add_yaxis("Cpu占有率散点图", y1)
         .add_yaxis("内存占有率散点图", y2)
        # .set_global_opts(title_opts=opts.TitleOpts(title="Cpu占有率散点图"))
     )
# 将折线图信息保存到文件中;
        line.render("show.html")

成果展示

计算机CPU占有率和内存占有率折线图

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用Python的psutil库获取系统CPU内存磁盘空间的使用情况,使用matplotlib库绘制折线图,使用smtplib库发送邮件报警。 以下是一个简单的示例代码: ```python import psutil import matplotlib.pyplot as plt import datetime import time import smtplib from email.mime.text import MIMEText from email.header import Header # 发送邮件报警 def send_email_alert(subject, content): mail_host = "smtp.xxx.com" # 邮箱服务器地址 mail_user = "your_email" # 邮箱账号 mail_pass = "your_password" # 邮箱密码 sender = 'your_email' # 发件人邮箱 receivers = ['receiver_email'] # 收件人邮箱列表 message = MIMEText(content, 'plain', 'utf-8') message['From'] = Header("System Monitor", 'utf-8') message['To'] = Header("Admin", 'utf-8') message['Subject'] = Header(subject, 'utf-8') try: smtpObj = smtplib.SMTP_SSL(mail_host, 465) smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) smtpObj.quit() print("邮件发送成功") except smtplib.SMTPException as e: print("Error: 无法发送邮件") print(e) # 获取CPU内存磁盘空间使用情况 def get_system_info(): cpu_percent = psutil.cpu_percent() mem_percent = psutil.virtual_memory().percent disk_percent = psutil.disk_usage('/').percent return cpu_percent, mem_percent, disk_percent # 绘制折线图 def plot_line_chart(x, y, title, xlabel, ylabel): fig, ax = plt.subplots() ax.plot(x, y) ax.set(xlabel=xlabel, ylabel=ylabel, title=title) ax.grid() plt.show() # 监控近一年系统使用情况 def monitor_system(): # 初始化数据 cpu_data = [] mem_data = [] disk_data = [] time_data = [] # 监控近一年系统使用情况 for i in range(365): cpu_percent, mem_percent, disk_percent = get_system_info() cpu_data.append(cpu_percent) mem_data.append(mem_percent) disk_data.append(disk_percent) time_data.append(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) time.sleep(3600) # 每隔一个小时获取一次数据 # 绘制折线图 plot_line_chart(time_data, cpu_data, 'CPU Usage', 'Time', 'CPU Usage (%)') plot_line_chart(time_data, mem_data, 'Memory Usage', 'Time', 'Memory Usage (%)') plot_line_chart(time_data, disk_data, 'Disk Usage', 'Time', 'Disk Usage (%)') # 发送邮件报警 if max(cpu_data) >= 90: subject = 'CPU usage is too high!' content = 'The CPU usage is {}% at {}.'.format(max(cpu_data), time_data[cpu_data.index(max(cpu_data))]) send_email_alert(subject, content) if max(mem_data) >= 90: subject = 'Memory usage is too high!' content = 'The memory usage is {}% at {}.'.format(max(mem_data), time_data[mem_data.index(max(mem_data))]) send_email_alert(subject, content) if max(disk_data) >= 90: subject = 'Disk usage is too high!' content = 'The disk usage is {}% at {}.'.format(max(disk_data), time_data[disk_data.index(max(disk_data))]) send_email_alert(subject, content) if __name__ == '__main__': monitor_system() ``` 这个示例代码会每隔一个小时获取一次系统CPU内存磁盘空间的使用情况,并绘制近一年的折线图。如果某个指标的最大值超过90%,则会发送邮件报警。你需要将`your_email`和`your_password`替换成实际的邮箱账号和密码,将`mail_host`替换成实际的邮箱服务器地址,将`receiver_email`替换成实际的收件人邮箱。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值