【实例代码分享】揭秘超强性能监控工具:Python psutil库

2395 篇文章 2 订阅
2261 篇文章 14 订阅

软件测试面试刷题,这个小程序(永久刷题),靠它可以快速找到工作!https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502icon-default.png?t=N7T8https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502

01前言

相信在做的各位都了解过cpu,内存,磁盘,这些在我们的工作中多多少少都会用的到,特别是做过性能测试的小伙们,为什么提到cpu,内存这些呢,主要今天给大家分享一个python的第3方库,可以用来检测电脑上的cpu或者服务器上的cpu变化。从而进行查看我们的性能状态。

02 psutil

psutil属于python跨平台使用的库,主要作用就是获取系统运行的进程和系统利用率(cpu,内存,磁盘)等信息,可以用于监控服务器和本地的性能指标。

03 安装

pip install psutil  安装psutil

04 常见功能

获取cpu信息

获取当前cpu信息,直接通过psutil库中的方法进行获取,其中interval=1表示1秒内的cpu值

import psutil


# 获取当前CPU
cpu = psutil.cpu_percent(interval=1)
print(f'目前CPU为:{cpu}%')

获取进程信息

获取当前进程信息,直接通过psutil库中的pids()进行获取

import psutil
# 获取当前pid号
pid = psutil.pids()
print('当前的pid列表:%s' %pid)

获取内存信息

获取当前内存信息,直接通过psutil库中的virtual_memory()进行获取。

import psutil
# 获取内存
mem = psutil.virtual_memory()
# 通过方法percent获取内存百分比
print(f'当前内存:{mem.percent}%')

获取当前磁盘信息

获取当前磁盘信息,直接通过psutil库中的disk_usage()其中'/' 参数表示要查询的磁盘分区或挂载点的路径

import psutil
# 获取磁盘分区
disk_=psutil.disk_partitions()
# 获取当前磁盘使用情况
disk = psutil.disk_usage('/')
# 通过方法percent获取内存百分比
print(disk)

05 实例

早上小明上班后,领导告诉他,我们目前的服务器的cpu和内存好像不稳定,让小明帮他写一个脚本然后统计下cpu和内存的变化,给到领导一个excel表格。

好在小明昨天看了这一篇文章,立刻有了灵感,打开pycharm就开始敲起来了

1、首先我们通过安装psutil库

2、分别通过获取cpu和内存

3、通过执行打印出来cpu和内存的值

import psutil
# 获取cpu的信息


def cpu():
    cpu = psutil.cpu_percent(interval=1)
    return cpu
    
# 获取内存的信息
def mem():
    mem = psutil.virtual_memory()
    return mem.percent
    
# 打印cpu和内存信息
def get_print(cpu,mem):
    print(f'当前Cpu:{cpu}%')
    print(f'当前内存:{mem}%')


a = cpu()
b = mem()
get_print(a,b)

通过cmd这里运行查看,发现已经可以单独获取成功当前的cpu和内存了

单独的已经完成了,那么是不是可以写一个循环,进行一直执行这个函数,在通过time函数进行增加间隔时间,然后小明的代码又敲起来了。

1、导入时间函数

2、通过for循环进行执行程序

import time
import psutil
# 获取cpu的信息


def cpu():
    cpu = psutil.cpu_percent(interval=1)
    return cpu
# 获取内存的信息
def mem():
    mem = psutil.virtual_memory()
    return mem.percent
# 打印cpu和内存信息
def get_print(cpu,mem):
    print(f'当前Cpu:{cpu}%')
    print(f'当前内存:{mem}%')
# 循环执行获取函数
for i in range(7200):
    a = cpu()
    b = mem()
    get_print(a,b)
    time.sleep(2)

通过运行结果可以看到,目前领导安排的任务已经完成了一半了,那么我们需要写入excel了,

这里小明想要先整理下打印的样式,于是又敲起来了代码

这里小明通过加入了时间函数获取了当前时间打印,加上了cpu和内存的值,优化了打印页面

import time
import psutil
# 获取cpu的信息


def cpu():
    cpu = psutil.cpu_percent(interval=1)
    return cpu
# 获取内存的信息
def mem():
    mem = psutil.virtual_memory()
    return mem.percent
# 打印cpu和内存信息
def get_print(cpu,mem):
    # 获取当前时间
    local_time = time.localtime(time.time())
    formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', local_time)
    print(formatted_time,f'当前Cpu:{cpu}%  当前内存:{mem}%')
# 循环执行获取函数
for i in range(7200):
    a = cpu()
    b = mem()
    get_print(a,b)
    time.sleep(2)

通过执行结果可以看出来,已经完成了,那么我们就只需要写入excel表格中了。

写入excel

这里小编使用的模块是pandas,也是属于python的第三方库,大多数用于数据处理,后续有机会给大家展示如何运用到测试当中。

import time
import pandas as pd
import psutil


def get_info():
    # 获取当前cpu
    cpu = psutil.cpu_percent(interval=1)
    # 获取当前内存
    mem = psutil.virtual_memory().percent
    # 获取当前时间
    local_time = time.localtime(time.time())
    formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', local_time)
    data = {'时间':[formatted_time],
            'cpu':[f'{cpu}%'],
            'mem':[f'{mem}%']
            }
    print(data)
    return data
filename = 'output.xlsx'
def write_info(data):
    new_df = pd.DataFrame(data)
    with pd.ExcelWriter(filename,mode='a',engine='openpyxl',if_sheet_exists='overlay') as writer:
        # 读取以前的数据
        existing_df = pd.read_excel(filename, sheet_name='Sheet1')
        # 合并新数据和已存在的数据
        appended_df = pd.concat([existing_df, new_df], ignore_index=True)
        # 写入合并后的新数据
        appended_df.to_excel(writer, sheet_name='Sheet1', index=False)
        
# 循环读取并写入excel中
while True:
    data = get_info()
    write_info(data)
    time.sleep(2)

通过运行后发现已经将对应的cpu和内存都写入到了excel表格中。

方法二:

上图中主要用于我们本地windows系统上,那么小明的领导需要用于服务器上,那么我们将我们的代码放到服务器上运行,因为前面介绍psutil库的时候介绍了,他是跨平台使用,可以在linux上和windows上进行运行。

通过将linux上所需要的环境内容都安装好了后,然后直接将代码上传到linux上,运行程序

06 总结

这里小编通过一个小小的问题,然后简单的介绍了如何通过python获取cpu和内存的过程,然后再介绍了pandas将我们抓取的cpu和内存放到excel中尽显存储。

本篇内容不是特别多,主要简单介绍了python的第三方库psutil。希望在后续的工作中,本篇文章能够帮助到您。

最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】

​​​软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

在这里插入图片描述

在这里插入图片描述

  • 12
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值