Python使用psutil实现系统监控与资源管理

Written by

in

文章目录
  • psutil 是“process and system utilities”的缩写,它是一个 跨平台的系统监控库,用于: 获取 CPU、内存、磁盘、网络 等系统使用情况 管理和获取 进程信息 实现任务监控、资源追踪和系统健康检查 提供类 Unix ps, top, df, netstat, lsof 等命令的功能接口 它的设计初衷是替代用 Python 封装 shell 命令的繁琐做法,提供一致、优雅、性能优异的 API。
  • 安装方式 使用 pip 安装非常简单: pip install psutil 安装完成后,几乎可以立即开始使用,无需额外配置。 快速示例:获取当前 CPU 使用率 import psutil print(“当前 CPU 使用率:”, psutil.cpu_percent(interval=1), “%”) cpu_percent() 表示在指定时间间隔内(如 1 秒)测量 CPU 总体使用率。
  • 你可以使用 psutil + rich 或 psutil + flask/streamlit 构建漂亮的图形或终端仪表盘。下面是一个简单的终端监控: import psutil import time import os def monitor(): while True: os.system(‘cls’ if os.name == ‘nt’ else ‘clear’) print(“=== 实时系统资源监控 ===”) print(f”CPU 使用率: {psutil.cpu_percent()}%”) mem = psutil.virtual_memory() print(f”内存: {mem.used / 1024 ** 3:.2f} GB / {mem.total / 1024 ** 3:.2f} GB ({mem.percent}%)”) net = psutil.net_io_counters() print(f”网络: 发送 {net.bytes_sent / 1024 ** 2:.2f} MB, 接收 {net.bytes_recv / 1024 ** 2:.2f} MB”) time.sleep(1) if __name__ == “__main__”: monitor() 可以扩展为 Web 仪表盘,甚至接入 Grafana、Prometheus 进行数据上报。
  • psutil 是一个非常成熟、稳定、文档完善的 Python 库,它几乎可以满足你对操作系统资源访问的一切需求,包括但不限于: 任务管理器替代脚本 DevOps 运维工具 系统性能分析 自动化测试平台 AI 训练任务资源调度 优势: 跨平台支持强(Windows/Linux/macOS) API 直观、结构清晰 文档丰富、社区活跃 可集成至各种 Python 工具链中 注意事项: 某些操作(如杀死进程、访问别的用户进程)可能需要管理员权限 大量遍历系统进程时注意异常处理(AccessDenied, NoSuchProcess) 到此这篇关于Python使用psutil实现系统监控与资源管理的文章就介绍到这了,更多相关Python psutil监控系统与资源内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: Python利用psutil库进行监控进程和资源 Python利用PsUtil实现实时监控系统状态 Python使用psutil库实现系统监控与管理详解 Python使用psutil库对系统数据进行采集监控的方法 python psutil监控进程实例 Python系统监控模块psutil功能与经典用法分析
  • 目录
    • 一、psutil 简介
    • 二、安装与基本使用
    • 三、CPU 信息监控
      • 1. 获取 CPU 逻辑/物理核心数
      • 2. 每个核心的使用率
      • 3. 获取 CPU 时间信息
    • 四、内存信息监控
      • 1. 获取虚拟内存使用情况
      • 2. 获取 swap 交换分区信息
    • 五、磁盘信息监控
      • 1. 获取磁盘分区信息
      • 2. 获取磁盘使用情况
      • 3. 实时磁盘 IO 情况
    • 六、网络信息监控
      • 1. 获取网络 IO 情况
      • 2. 获取网卡信息
      • 3. 当前网络连接
    • 七、进程管理
      • 1. 枚举当前所有进程
      • 2. 获取指定进程的详细信息
      • 3. 操作进程(终止、挂起、恢复)
    • 八、构建一个简单的系统资源仪表板
      • 九、高级用法与实践案例
        • 1. 编写一个自动杀死高 CPU 占用进程的守护脚本
        • 2. 跨平台性能分析工具
      • 十、总结与展望

        在系统运维、资源监控、性能分析、服务状态诊断等领域,开发者常常需要获取操作系统底层信息,如 CPU 使用率、内存占用、磁盘读写、网络传输、进程详情等。虽然这些功能可以通过 shell 命令实现,如 top、df、ps、iostat 等,但在自动化脚本和跨平台开发中,使用 Python 脚本来完成这些任务更具灵活性和可移植性。

        这正是 psutil 的用武之地 —— 一个功能强大的跨平台系统监控库,可以轻松获取各种系统资源状态和进程信息,且支持 Linux、Windows、macOS 等平台。

        本文将深入讲解 psutil 的各项功能,并结合实际代码示例,展示如何用 Python 构建自己的系统监控工具、资源分析器、进程管理脚本等。

        psutil 是“process and system utilities”的缩写,它是一个 跨平台的系统监控库,用于:

        • 获取 CPU、内存、磁盘、网络 等系统使用情况
        • 管理和获取 进程信息
        • 实现任务监控、资源追踪和系统健康检查
        • 提供类 Unix ps, top, df, netstat, lsof 等命令的功能接口

        它的设计初衷是替代用 Python 封装 shell 命令的繁琐做法,提供一致、优雅、性能优异的 API。

        安装方式

        使用 pip 安装非常简单:

        pip install psutil
        

        安装完成后,几乎可以立即开始使用,无需额外配置。

        快速示例:获取当前 CPU 使用率

        import psutil
        
        print("当前 CPU 使用率:", psutil.cpu_percent(interval=1), "%")
        

        cpu_percent() 表示在指定时间间隔内(如 1 秒)测量 CPU 总体使用率。

        print("物理核心数:", psutil.cpu_count(logical=False))
        print("逻辑核心数:", psutil.cpu_count(logical=True))
        

        import time
        
        for _ in range(5):
            usage = psutil.cpu_percent(interval=1, percpu=True)
            print("每个核心使用率:", usage)
        

        times = psutil.cpu_times()
        print(f"user: {times.user}, system: {times.system}, idle: {times.idle}")
        

        这个 API 提供了系统级的 CPU 时间分布。

        mem = psutil.virtual_memory()
        print(f"总内存: {mem.total / 1024 ** 3:.2f} GB")
        print(f"已使用: {mem.used / 1024 ** 3:.2f} GB")
        print(f"空闲: {mem.available / 1024 ** 3:.2f} GB")
        print(f"使用率: {mem.percent}%")
        

        swap = psutil.swap_memory()
        print(f"Swap 总量: {swap.total / 1024 ** 3:.2f} GB")
        print(f"使用率: {swap.percent}%")
        

        partitions = psutil.disk_partitions()
        for p in partitions:
            print(f"挂载点: {p.mountpoint}, 类型: {p.fstype}")
        

        usage = psutil.disk_usage('/')
        print(f"总空间: {usage.total / 1024 ** 3:.2f} GB")
        print(f"已用: {usage.used / 1024 ** 3:.2f} GB")
        print(f"剩余: {usage.free / 1024 ** 3:.2f} GB")
        

        io = psutil.disk_io_counters()
        print(f"读字节: {io.read_bytes / 1024 ** 2:.2f} MB")
        print(f"写字节: {io.write_bytes / 1024 ** 2:.2f} MB")
        

        net = psutil.net_io_counters()
        print(f"发送: {net.bytes_sent / 1024 ** 2:.2f} MB")
        print(f"接收: {net.bytes_recv / 1024 ** 2:.2f} MB")
        

        addrs = psutil.net_if_addrs()
        for iface, infos in addrs.items():
            print(f"n网卡: {iface}")
            for info in infos:
                print(f"  地址: {info.address} ({info.family})")
        

        conns = psutil.net_connections(kind='inet')
        for conn in conns[:5]:
            print(f"连接: {conn.laddr} -> {conn.raddr}, 状态: {conn.status}")
        

        for proc in psutil.process_iter(['pid', 'name', 'username']):
            print(proc.info)
        

        p = psutil.Process(1)  # PID 1 通常是 init 或 systemd
        print(f"名称: {p.name()}")
        print(f"路径: {p.exe()}")
        print(f"状态: {p.status()}")
        print(f"CPU使用率: {p.cpu_percent(interval=1.0)}")
        print(f"内存使用: {p.memory_info().rss / 1024 ** 2:.2f} MB")
        

        p = psutil.Process(1234)
        p.suspend()  # 挂起
        p.resume()   # 恢复
        p.terminate()  # 终止
        

        注意:需要管理员权限或 root 权限才能操作其他用户的进程。

        你可以使用 psutil + rich 或 psutil + flask/streamlit 构建漂亮的图形或终端仪表盘。下面是一个简单的终端监控:

        import psutil
        import time
        import os
        
        def monitor():
            while True:
                os.system('cls' if os.name == 'nt' else 'clear')
                print("=== 实时系统资源监控 ===")
                print(f"CPU 使用率: {psutil.cpu_percent()}%")
                mem = psutil.virtual_memory()
                print(f"内存: {mem.used / 1024 ** 3:.2f} GB / {mem.total / 1024 ** 3:.2f} GB ({mem.percent}%)")
                net = psutil.net_io_counters()
                print(f"网络: 发送 {net.bytes_sent / 1024 ** 2:.2f} MB, 接收 {net.bytes_recv / 1024 ** 2:.2f} MB")
                time.sleep(1)
        
        if __name__ == "__main__":
            monitor()

        可以扩展为 Web 仪表盘,甚至接入 Grafana、Prometheus 进行数据上报。

        def auto_kill(threshold=80):
            for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):
                try:
                    if proc.info['cpu_percent'] > threshold:
                        print(f"杀死高 CPU 进程: {proc.info}")
                        psutil.Process(proc.info['pid']).terminate()
                except (psutil.NoSuchProcess, psutil.AccessDenied):
                    continue
        

        你可以用 psutil 收集数据并记录日志:

        import json
        import datetime
        
        def log_stats():
            stats = {
                "time": str(datetime.datetime.now()),
                "cpu": psutil.cpu_percent(),
                "mem": psutil.virtual_memory().percent,
                "disk": psutil.disk_usage('/').percent,
            }
            with open("syslog.json", "a") as f:
                f.write(json.dumps(stats) + "n")
        

        可用于机器长时间运行状态监控和可视化分析。

        psutil 是一个非常成熟、稳定、文档完善的 Python 库,它几乎可以满足你对操作系统资源访问的一切需求,包括但不限于:

        • 任务管理器替代脚本
        • DevOps 运维工具
        • 系统性能分析
        • 自动化测试平台
        • AI 训练任务资源调度

        优势:

        • 跨平台支持强(Windows/Linux/macOS)
        • API 直观、结构清晰
        • 文档丰富、社区活跃
        • 可集成至各种 Python 工具链中

        注意事项:

        • 某些操作(如杀死进程、访问别的用户进程)可能需要管理员权限
        • 大量遍历系统进程时注意异常处理(AccessDenied, NoSuchProcess)

        到此这篇关于Python使用psutil实现系统监控与资源管理的文章就介绍到这了,更多相关Python psutil监控系统与资源内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

        您可能感兴趣的文章:

        • Python利用psutil库进行监控进程和资源
        • Python利用PsUtil实现实时监控系统状态
        • Python使用psutil库实现系统监控与管理详解
        • Python使用psutil库对系统数据进行采集监控的方法
        • python psutil监控进程实例
        • Python系统监控模块psutil功能与经典用法分析

        站内搜索