R / Richie全部文章 ↑

Python · 5 分钟阅读

`psutil`:系统性能信息库

目录


psutil(process and system utilities)是跨平台的系统监控库:
CPU / 内存 / 磁盘 / 网络 / 进程 / 传感器。能替代 ps / top / lsof /
netstat / ifconfig / who / df / kill / free / uptime 等
命令行工具,是后端监控和系统资源管理的事实标准。


1. 安装

pip install -U psutil
import psutil
print(psutil.__version__)

Linux 上若要监控 GPU / 电池 / 温度,需 pip install psutil[sensors]。


2. CPU

import psutil

# 物理 / 逻辑 CPU 数
print("logical:", psutil.cpu_count())         # 全部
print("physical:", psutil.cpu_count(logical=False))

# 总体 CPU 时间细分
print(psutil.cpu_times())
# scputimes(user=..., system=..., idle=..., interrupt=..., dpc=...)

# 总体 CPU 使用率(百分比,需要一个采样间隔)
print(f"CPU%: {psutil.cpu_percent(interval=1):.1f}")

# 各逻辑 CPU 的使用率(列表)
print(psutil.cpu_percent(interval=1, percpu=True))

# 各 CPU 的时间细分
print(psutil.cpu_times(percpu=True))

cpu_percent(interval=...) 是“上次调用到这次调用”的差值;第一次调用
通常返回 0.0
,再调一次才拿到真实值。


3. 内存

mem = psutil.virtual_memory()
print(f"total    : {mem.total / 1024**3:.2f} GiB")
print(f"available: {mem.available / 1024**3:.2f} GiB")
print(f"used     : {mem.used / 1024**3:.2f} GiB")
print(f"percent  : {mem.percent:.1f}%")

字段含义:

字段 含义
total 物理内存总数
available 不含 swap 也能用的内存(推荐看这个)
used 已用内存(≈ total - free - buffers - cached)
free 完全空闲
percent (total - available) / total

交换分区:

swap = psutil.swap_memory()
print(swap.total, swap.used, swap.percent)

4. 磁盘

# 1) 物理分区
for part in psutil.disk_partitions():
    print(part.device, part.mountpoint, part.fstype, part.opts)

# 2) 单个挂载点的使用率
print(psutil.disk_usage("/"))

# 3) 全局 / 每分区的 IO
print(psutil.disk_io_counters())         # 全部
print(psutil.disk_io_counters(perdisk=True))

常用字段:

disk_io_counters 字段 含义
read_count / write_count 读写 IO 次数
read_bytes / write_bytes 读写字节数
read_time / write_time 读写耗时(ms)

5. 网络

# 全局
print(psutil.net_io_counters())
# 每网卡
print(psutil.net_io_counters(pernic=True))

# 当前连接(需要 root 看全部)
print(psutil.net_connections(kind="tcp")[:3])

字段:bytes_sent / bytes_recv / packets_sent / packets_recv /
errin / errout / dropin / dropout。

查“哪些进程在监听 80 端口”:

for c in psutil.net_connections(kind="tcp"):
    if c.laddr and c.laddr.port == 80 and c.status == "LISTEN":
        print(c.pid, c.laddr, c.raddr)

6. 进程管理

6.1 列出所有进程

for p in psutil.process_iter(["pid", "name"]):
    print(p.info)

6.2 拿单个进程

p = psutil.Process(104)            # PID
print(p.name())                    # 进程名
print(p.exe())                     # 启动路径
print(p.cwd())                     # 工作目录
print(p.status())                  # running / sleeping / stopped ...
print(p.create_time())             # 启动时间戳
print(p.username())                # 所属用户
print(p.cpu_percent(interval=0.1))
print(p.memory_info())             # rss / vms
print(p.io_counters())             # 读 / 写 IO
print(p.num_threads())
print(p.connections(kind="tcp"))

Process 是懒加载:只有访问属性时才会触发 os 调用。

6.3 进程操作

p.suspend()           # 挂起(SIGSTOP)
p.resume()            # 恢复(SIGCONT)
p.terminate()         # SIGTERM
p.kill()              # SIGKILL
p.wait(timeout=3)     # 等待结束

# 设置 CPU 亲和度
p.cpu_affinity([0, 1])    # 限制到 CPU 0 和 1

6.4 用 psutil 跑外部进程

from subprocess import PIPE
import psutil

p = psutil.Popen(["/usr/bin/python", "-c", "print('hi')"], stdout=PIPE)
print(p.name())                        # python
p.communicate(timeout=5)
print(p.username(), p.cpu_times())

psutil.Popen 是 subprocess.Popen 的超集,额外提供 cpu_times、
memory_info 等方法。


7. 其它常用接口

接口 作用
psutil.users() 当前登录用户
psutil.boot_time() 系统启动时间戳
psutil.sensors_battery() 笔记本电池(Linux)
psutil.sensors_temperatures() 温度(需要 psutil[sensors])
psutil.net_if_addrs() 网卡地址
psutil.net_if_stats() 网卡统计(isup / speed / mtu)
psutil.pids() 所有 PID
import psutil, datetime
boot = datetime.datetime.fromtimestamp(psutil.boot_time())
print("uptime since:", boot)

8. 实战:系统资源监控

import time
import psutil


def report(interval: float = 1.0) -> None:
    while True:
        cpu = psutil.cpu_percent(interval=interval)
        mem = psutil.virtual_memory().percent
        disk = psutil.disk_usage("/").percent
        net = psutil.net_io_counters()

        print(
            f"cpu={cpu:5.1f}%  mem={mem:5.1f}%  "
            f"disk={disk:5.1f}%  "
            f"net_sent={net.bytes_sent/1024/1024:.1f}MB  "
            f"net_recv={net.bytes_recv/1024/1024:.1f}MB"
        )
        # 注意:cpu_percent/interval 已经睡过,循环不必再 sleep


if __name__ == "__main__":
    report()

9. 常见问题

  • NoSuchProcess:进程已退出,访问属性会抛。捕获后跳过即可。
  • AccessDenied:无权限(如跨用户查进程)。退化为只查 pid / name。
  • 第一次 cpu_percent 是 0.0:必须间隔一段时间二次调用。
  • macOS / Windows:cpu_times 字段名不一样(macOS 没有 interrupt / dpc)。
  • 高频轮询:psutil.cpu_percent(interval=0) 立即返回 0 或上次差值;想拿
    真实值就 interval=0.5 或自己定时采样。

10. 小结

  • psutil 跨平台把 ps / top / df / free / ifconfig / netstat 等 CLI 工具
    全部变成 Python API。
  • 监控时拿 cpu_percent(interval=...) / virtual_memory().percent /
    disk_usage('/').percent 三件套就够覆盖 90% 场景。
  • 进程管理注意 Process 是懒加载;用 process_iter(attrs=[...]) 一次拿多列字段
    更高效。
  • 真正做监控建议配套 prometheus_client / opentelemetry,把 psutil 数据
    打点成指标。