ai
  • index
  • 1.首页
  • 2.介绍
  • 3.架构概览
  • 4.服务器概念
  • 5.客户端概念
  • 6.版本控制
  • 7.连接到远程MCP服务器
  • 8.连接到本地MCP服务器
  • json_rpc
  • 9.构建一个MCP服务器
  • 10.检查员
  • 11.构建一个MCP客户端
  • 14.架构
  • 15.基础协议概述
  • 16.生命周期
  • 17.传输
  • 18.授权
  • 19.安全最佳实践
  • 20.取消
  • 21.Ping
  • 22.进展
  • 23.Roots
  • 24.采样
  • 25.启发
  • 26.服务器特性
  • 27.提示词
  • 28.资源
  • 29.工具
  • 30.完成
  • 31.日志记录
  • 32.分页
  • 33.架构参考
  • URI模板
  • 12.实现
  • http.server
  • 动态客户端注册协议
  • 受保护资源元数据
  • 授权服务器元数据
  • JWKS
  • PKCE
  • PyJWT
  • secrets
  • watchfiles
  • 实现authorization
  • 实现cancel
  • 实现completion
  • 实现logging
  • 实现pagination
  • 实现process
  • 实现transport
  • psutil
  • pytz
  • zoneinfo
  • contextlib
  • Starlette
  • mcp.1.starter
  • mcp.2.Resource
  • mcp.3.structured_output
  • mcp.4.prompts
  • mcp.5.context
  • mcp.6.streamable
  • mcp.7.lowlevel
  • mcp.8.Completion
  • mcp.9.Elicitation
  • mcp.10.oauth
  • mcp.11.integration
  • mcp.12.best
  • mysql-mcp
  • databases
  • uvicorn
  • asynccontextmanager
  • AsyncExitStack
  • streamable
  • aiohttp
  • publish
  • email
  • schedule
  • twine
  • 1.教学文档总览
  • 2.教师使用指南
  • 3.教学系统快速参考
  • 4.新生入门指南
  • 5.学生使用指南
  • 1. psutil 是什么?
  • 2. 核心功能与常用 API
    • 2.1 系统整体信息
    • 2.2 内存信息
    • 2.3 磁盘信息
    • 2.4 网络信息
    • 2.5 进程管理
  • 3. 实际应用场景
  • 4. 安装与注意事项
    • 4.1 安装
    • 4.2 注意事项

1. psutil 是什么? #

psutil(process and system utilities)是一个跨平台的库,用于在 Python 中获取系统和进程的运行信息,包括:

  • CPU 使用率
  • 内存 使用情况(物理内存、交换分区)
  • 磁盘 分区、IO 统计
  • 网络 连接、IO 统计
  • 正在运行的进程 管理和详细信息

它的核心价值在于:

  1. 跨平台:支持 Windows, Linux, macOS, FreeBSD, OpenBSD, Solaris 等,API 接口完全一致。
  2. 功能强大:提供了几乎所有系统监控工具(如 top, htop, netstat, taskmgr 等)能提供的信息。
  3. 易于使用:API 设计非常直观,几行代码就能获取关键系统指标。

2. 核心功能与常用 API #

2.1 系统整体信息 #

CPU 信息

import psutil

# 获取 CPU 逻辑核心数量
print(f"逻辑 CPU 数量: {psutil.cpu_count()}")

# 获取 CPU 物理核心数量
print(f"物理 CPU 数量: {psutil.cpu_count(logical=False)}")

# 获取 CPU 当前使用率(间隔 1 秒)
cpu_percent = psutil.cpu_percent(interval=1)
print(f"CPU 总使用率: {cpu_percent}%")

# 获取每个 CPU 核心的使用率
cpu_percent_per_core = psutil.cpu_percent(interval=1, percpu=True)
for i, percent in enumerate(cpu_percent_per_core):
    print(f"CPU 核心 {i} 使用率: {percent}%")

# 获取 CPU 频率(当前、最小、最大)
cpu_freq = psutil.cpu_freq()
print(f"当前频率: {cpu_freq.current}MHz")
print(f"最小频率: {cpu_freq.min}MHz")
print(f"最大频率: {cpu_freq.max}MHz")

# 获取 CPU 状态信息(用户/系统/空闲时间等)
cpu_times = psutil.cpu_times()
print(f"用户模式运行时间: {cpu_times.user} 秒")
print(f"系统内核模式运行时间: {cpu_times.system} 秒")
print(f"空闲时间: {cpu_times.idle} 秒")

2.2 内存信息 #

import psutil

# 获取物理内存信息
mem = psutil.virtual_memory()
print(f"总内存: {mem.total / (1024**3):.2f} GB") # 转换为 GB
print(f"可用内存: {mem.available / (1024**3):.2f} GB")
print(f"已用内存: {mem.used / (1024**3):.2f} GB")
print(f"内存使用百分比: {mem.percent}%")

# 获取交换分区(虚拟内存)信息
swap = psutil.swap_memory()
print(f"交换分区总量: {swap.total / (1024**3):.2f} GB")
print(f"交换分区使用量: {swap.used / (1024**3):.2f} GB")
print(f"交换分区使用百分比: {swap.percent}%")

2.3 磁盘信息 #

import psutil

# 获取磁盘分区信息
partitions = psutil.disk_partitions()
for partition in partitions:
    print(f"设备: {partition.device}")
    print(f"挂载点: {partition.mountpoint}")
    print(f"文件系统类型: {partition.fstype}")
    print("---")

# 获取指定分区的使用情况(例如 C盘 或 /)
disk_usage = psutil.disk_usage('/') # Windows 可用 'C:\\'
print(f"磁盘总空间: {disk_usage.total / (1024**3):.2f} GB")
print(f"磁盘已用空间: {disk_usage.used / (1024**3):.2f} GB")
print(f"磁盘空闲空间: {disk_usage.free / (1024**3):.2f} GB")
print(f"磁盘使用百分比: {disk_usage.percent}%")

# 获取磁盘 IO 统计(读写次数、字节数)
disk_io = psutil.disk_io_counters()
print(f"磁盘读取次数: {disk_io.read_count}")
print(f"磁盘写入次数: {disk_io.write_count}")
print(f"磁盘读取字节数: {disk_io.read_bytes / (1024**2):.2f} MB")
print(f"磁盘写入字节数: {disk_io.write_bytes / (1024**2):.2f} MB")

2.4 网络信息 #

import psutil

# 获取网络 IO 统计(所有网卡总和)
net_io = psutil.net_io_counters()
print(f"发送字节数: {net_io.bytes_sent / (1024**2):.2f} MB")
print(f"接收字节数: {net_io.bytes_recv / (1024**2):.2f} MB")
print(f"发送数据包数: {net_io.packets_sent}")
print(f"接收数据包数: {net_io.packets_recv}")

# 获取当前网络连接信息
# kind 可选 'inet' (IPv4), 'inet6' (IPv6), 'tcp', 'udp', 'unix' 等
connections = psutil.net_connections(kind='inet')
for conn in connections:
    print(f"协议: {conn.type}")
    print(f"本地地址: {conn.laddr}")
    print(f"远程地址: {conn.raddr}")
    print(f"状态: {conn.status}")
    print("---")

# 获取网络接口信息(每个网卡的状态和统计)
net_if_addrs = psutil.net_if_addrs() # 获取地址信息
net_if_stats = psutil.net_if_stats() # 获取状态信息(是否启动、速度等)
for interface_name, interface_addresses in net_if_addrs.items():
    print(f"网卡名: {interface_name}")
    for address in interface_addresses:
        print(f"  地址族: {address.family}, 地址: {address.address}, 掩码: {address.netmask}")
    stats = net_if_stats.get(interface_name)
    if stats:
        print(f"  是否启动: {stats.isup}")
        print(f"  速度: {stats.speed} Mbps")
    print("---")

2.5 进程管理 #

这是 psutil 最强大的功能之一。

import psutil

# 获取所有进程的 PID 列表
all_pids = psutil.pids()
print(f"当前运行中的进程数: {len(all_pids)}")

# 迭代所有进程
for proc in psutil.process_iter(['pid', 'name', 'username']):
    try:
        # 获取进程信息
        info = proc.info
        print(f"PID: {info['pid']}, 名称: {info['name']}, 用户: {info['username']}")
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
        # 处理进程已结束、无权限、僵尸进程等异常
        pass

# 根据 PID 查找特定进程
try:
    pid = 1234 # 替换为你要查找的 PID
    process = psutil.Process(pid)
    print(f"进程名: {process.name()}")
    print(f"进程状态: {process.status()}")
    print(f"进程执行路径: {process.exe()}")
    print(f"进程工作目录: {process.cwd()}")
    print(f"进程命令行: {process.cmdline()}")
    print(f"进程启动时间: {process.create_time()}") # 时间戳
    print(f"进程用户名: {process.username()}")
    print(f"进程 CPU 使用率: {process.cpu_percent(interval=0.1)}%")
    print(f"进程内存使用率: {process.memory_percent()}%")
    mem_info = process.memory_info()
    print(f"进程物理内存使用 (RSS): {mem_info.rss / (1024**2):.2f} MB")
    print(f"进程虚拟内存使用 (VMS): {mem_info.vms / (1024**2):.2f} MB")

    # 获取进程的线程信息
    threads = process.threads()
    print(f"线程数量: {len(threads)}")

    # 获取进程打开的文件(Unix-like 系统)
    # files = process.open_files()
    # for f in files:
    #     print(f.path)

    # 获取进程的网络连接
    # connections = process.connections()
    # for conn in connections:
    #     print(conn.laddr, conn.raddr, conn.status)

except psutil.NoSuchProcess:
    print(f"PID {pid} 对应的进程不存在")
except psutil.AccessDenied:
    print(f"无权限访问 PID {pid} 的进程信息")

# 终止进程
# process.terminate() # 发送 SIGTERM (Unix) / 温和终止 (Windows)
# process.kill()      # 发送 SIGKILL (Unix) / 强制终止 (Windows)

3. 实际应用场景 #

  1. 系统监控工具:编写类似 top, htop, glances 的监控脚本或桌面应用。
  2. 资源限制:监控某个特定进程或自身的资源消耗,超过阈值时告警或采取行动。
  3. 进程管理:查找、筛选、管理特定进程(例如,找到所有 Chrome 进程并获取其资源占用)。
  4. 性能分析:在性能测试中,同时记录系统的 CPU、内存、磁盘 IO 等指标,辅助分析瓶颈。
  5. 安全工具:检测异常网络连接或可疑进程。
  6. 运维脚本:自动化运维任务,如监控磁盘空间并在不足时发送通知。

4. 安装与注意事项 #

4.1 安装 #

使用 pip 或 uv 安装非常简单:

pip install psutil
# 或者
uv pip install psutil

4.2 注意事项 #

  • 权限问题:获取其他用户进程的详细信息或系统全局信息可能需要 root 或 Administrator 权限。
  • 异常处理:进程是动态的,可能在查询的瞬间就结束了。使用 try-except 块处理 NoSuchProcess, AccessDenied, ZombieProcess 等异常是最佳实践。
  • 性能开销:频繁调用某些函数(如 cpu_percent(interval=0.1))可能会带来少量性能开销,在生产环境中需注意采样频率。

总之,psutil 是 Python 生态中系统监控领域的绝对霸主,API 设计优雅,功能全面且稳定,是开发运维、监控、系统工具类应用的必备神器。

访问验证

请输入访问令牌

Token不正确,请重新输入