Python利用psutil库进行监控进程和资源

转载:https://www.jianshu.com/p/0deff60c5c96

目录

主要功能

1. 获取系统信息

2. 进程管理

实际应用场景

1. 监控系统资源

2. 进程管理

3. 监控 Web 服务器性能

4. 监控后台任务的资源消耗

高级功能

1. 监控进程的子进程

2. 监控进程的文件IO

3. 监控进程的网络连接

====监控资源信息写入文件的实例代码=======


psutil 是一个跨平台的 Python 库,旨在提供对系统资源和进程的高级别接口。它不仅支持 Windows、Linux 和 macOS 等主流操作系统,还提供了一致的 API,使得在不同平台上编写的代码具有较高的可移植性。psutil 不仅易于使用,而且功能丰富,可以满足各种系统监控和进程管理的需求。

主要功能

1. 获取系统信息

psutil 提供了丰富的函数来获取有关系统的各种信息,包括 CPU、内存、磁盘、网络等方面的数据。

以下是一些常用的系统信息获取函数:

  • psutil.cpu_percent():获取 CPU 使用率。
  • psutil.virtual_memory():获取内存使用情况。
  • psutil.disk_usage('/'):获取指定磁盘分区的使用情况。
  • psutil.net_io_counters():获取网络 I/O 统计信息。

2. 进程管理

psutil 使得管理系统中运行的进程变得非常简单。通过 psutil 提供的函数,可以轻松地获取进程列表、查找特定进程、终止进程等。

以下是一些常用的进程管理函数:

  • psutil.pids():获取当前所有进程的 PID 列表。
  • psutil.Process(pid):通过 PID 获取进程对象。
  • process.cpu_percent():获取指定进程的 CPU 使用率。
  • process.memory_info():获取指定进程的内存使用情况。
  • process.terminate():终止指定进程。

实际应用场景

1. 监控系统资源

import psutil

# 获取 CPU 使用率
cpu_usage = psutil.cpu_percent()
print("CPU Usage:", cpu_usage)

# 获取内存使用情况
mem_info = psutil.virtual_memory()
print("Memory Usage:", mem_info)

# 获取磁盘使用情况
disk_usage = psutil.disk_usage('/')
print("Disk Usage:", disk_usage)

# 获取网络 I/O 统计信息
net_io = psutil.net_io_counters()
print("Network I/O:", net_io)

2. 进程管理

import psutil

# 获取所有进程列表
all_processes = psutil.pids()
print("All Processes:", all_processes)

# 查找特定进程
for pid in all_processes:
    process = psutil.Process(pid)
    if 'python' in process.name():
        print("Python Process Found:", process)

# 终止指定进程
# process.terminate()

3. 监控 Web 服务器性能

import psutil
import time

def monitor_server_performance():
    while True:
        # 获取 CPU 使用率
        cpu_usage = psutil.cpu_percent()
        print("CPU Usage:", cpu_usage)

        # 获取内存使用情况
        mem_info = psutil.virtual_memory()
        print("Memory Usage:", mem_info)

        # 休眠 1 秒
        time.sleep(1)

monitor_server_performance()

4. 监控后台任务的资源消耗

import psutil

def monitor_background_tasks():
    while True:
        # 获取指定进程的 CPU 使用率
        process = psutil.Process(pid)
        cpu_percent = process.cpu_percent()
        print("Background Task CPU Usage:", cpu_percent)

        # 获取指定进程的内存使用情况
        mem_info = process.memory_info()
        print("Background Task Memory Usage:", mem_info)

        # 休眠 10 秒
        time.sleep(10)

monitor_background_tasks()

高级功能

除了常规的系统监控和进程管理功能之外,psutil 还提供了一些高级功能,可以进一步增强其实用性和灵活性。

1. 监控进程的子进程

通过 psutil,可以轻松地监控一个进程的所有子进程,并获取它们的详细信息。这对于某些需要管理多个相关进程的应用程序来说尤为重要。

import psutil

# 获取指定进程的所有子进程
parent_process = psutil.Process(pid)
children = parent_process.children(recursive=True)
print("Children Processes:", children)

2. 监控进程的文件IO

psutil 还支持监控进程的文件 IO 操作,包括读写操作的次数和字节数等信息。这对于诊断进程的性能问题或查找异常操作非常有用。

import psutil

# 获取指定进程的文件 IO 统计信息
process = psutil.Process(pid)
io_counters = process.io_counters()
print("IO Counters:", io_counters)

3. 监控进程的网络连接

psutil 可以查看指定进程当前建立的所有网络连接,包括连接的远程地址和端口等信息。这对于网络相关的应用程序监控和安全审计非常有帮助。

import psutil

# 获取指定进程的网络连接列表
process = psutil.Process(pid)
connections = process.connections()
print("Network Connections:", connections)

====监控资源信息写入文件的实例代码=======

filename = 'systemInfo.txt'

#open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):

while True:

    curTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    #print(f'cpu usage: {psutil.cpu_percent(interval=2)})');
    cpuUse = psutil.cpu_percent(interval=2)

    # 获取内存信息
    virtual_mem = psutil.virtual_memory()
    memory_total = virtual_mem.total / (1024 ** 3)  # 转换为GB
    memory_available = virtual_mem.available / (1024 ** 3)  # 转换为GB
    memory_used = virtual_mem.used / (1024 ** 3)  # 转换为GB
    memory_percent = virtual_mem.percent


    with open(filename, mode='a') as file:
        file.write(f"{curTime}: cpuUsage:{cpuUse}\n");
        file.write(f"{curTime}: Memory Total: {memory_total:.2f} GB\n")
        file.write(f"{curTime}: Memory Available: {memory_available:.2f} GB\n")
        file.write(f"{curTime}: Memory Used: {memory_used:.2f} GB\n")
        file.write(f"{curTime}: Memory Percent Used: {memory_percent}%\n\n")

    time.sleep(5);




 


相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-21 22:14:03       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-21 22:14:03       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-21 22:14:03       45 阅读
  4. Python语言-面向对象

    2024-07-21 22:14:03       55 阅读

热门阅读

  1. SpringBoot RestHighLevelClient 按版本更新

    2024-07-21 22:14:03       20 阅读
  2. 跨域问题几种解决方法

    2024-07-21 22:14:03       20 阅读
  3. Python面试整理-文件处理

    2024-07-21 22:14:03       15 阅读
  4. 分式

    2024-07-21 22:14:03       18 阅读
  5. Spring WebFlux 介绍与效果演示示例

    2024-07-21 22:14:03       17 阅读
  6. django 需要修改的文件

    2024-07-21 22:14:03       21 阅读
  7. Random,ThreadLocalRandom,SecureRandom有什么区别

    2024-07-21 22:14:03       18 阅读
  8. Python 爬虫技术 第05节 异常处理

    2024-07-21 22:14:03       20 阅读
  9. 微信小程序开发:DOM 相关 API 使用详解

    2024-07-21 22:14:03       15 阅读
  10. QtQuick-QML语法

    2024-07-21 22:14:03       16 阅读
  11. Codeforces Round 960 (Div. 2)VP

    2024-07-21 22:14:03       20 阅读
  12. WebAssembly在前端开发中的创新与应用

    2024-07-21 22:14:03       16 阅读
  13. easyExcel

    easyExcel

    2024-07-21 22:14:03      16 阅读
  14. 什么是等保测评

    2024-07-21 22:14:03       16 阅读
  15. acml可用订阅到起始位姿

    2024-07-21 22:14:03       18 阅读
  16. Windows 12 网页版

    2024-07-21 22:14:03       17 阅读