Python psutil 工具详解与使用指南

546 阅读4分钟

Python psutil 工具详解与使用指南

简介

psutil(process and system utilities)是 Python 中一个强大的跨平台库,用于获取系统信息和管理系统进程。通过 psutil,开发者可以轻松访问 CPU、内存、磁盘、网络、传感器等信息,还能进行进程管理操作,比如终止进程、查看进程资源占用等。

在本文中,我们将详细介绍 psutil 的功能及其常见用法,并通过代码示例帮助读者快速掌握该工具。


安装 psutil

在开始使用前,需要安装 psutil,可以使用以下命令:

pip install psutil

psutil 的主要功能

psutil 提供了丰富的系统信息和进程管理功能,其主要功能包括:

  1. 系统信息

    • CPU 信息
    • 内存信息
    • 磁盘信息
    • 网络信息
    • 传感器信息(如温度、电池等)
  2. 进程管理

    • 获取进程信息
    • 终止、挂起、恢复进程
    • 获取当前运行进程的快照

1. 获取 CPU 信息

获取 CPU 总览信息

psutil 提供了多种方式来获取 CPU 的使用情况和性能信息:

import psutil
​
# 获取 CPU 的逻辑核心数
logical_cores = psutil.cpu_count(logical=True)
print(f"逻辑核心数:{logical_cores}")
​
# 获取 CPU 的物理核心数
physical_cores = psutil.cpu_count(logical=False)
print(f"物理核心数:{physical_cores}")
​
# 获取每个核心的使用率(百分比)
cpu_percent_per_core = psutil.cpu_percent(interval=1, percpu=True)
print(f"每个核心的使用率:{cpu_percent_per_core}")
​
# 获取总的 CPU 使用率
cpu_percent_total = psutil.cpu_percent(interval=1)
print(f"总的 CPU 使用率:{cpu_percent_total}%")

获取 CPU 时间占比

psutil.cpu_times() 返回 CPU 时间的详细信息:

cpu_times = psutil.cpu_times()
print("CPU 时间占比:")
print(f"用户时间:{cpu_times.user} 秒")
print(f"系统时间:{cpu_times.system} 秒")
print(f"空闲时间:{cpu_times.idle} 秒")

2. 获取内存信息

psutil 提供了 virtual_memoryswap_memory 两个方法,用于获取虚拟内存和交换内存的信息。

虚拟内存信息

mem_info = psutil.virtual_memory()
​
print("虚拟内存信息:")
print(f"总内存:{mem_info.total / 1024 / 1024:.2f} MB")
print(f"已用内存:{mem_info.used / 1024 / 1024:.2f} MB")
print(f"剩余内存:{mem_info.available / 1024 / 1024:.2f} MB")
print(f"内存使用率:{mem_info.percent}%")

交换内存信息

swap_info = psutil.swap_memory()
​
print("交换内存信息:")
print(f"总交换区:{swap_info.total / 1024 / 1024:.2f} MB")
print(f"已用交换区:{swap_info.used / 1024 / 1024:.2f} MB")
print(f"剩余交换区:{swap_info.free / 1024 / 1024:.2f} MB")
print(f"交换区使用率:{swap_info.percent}%")

3. 获取磁盘信息

磁盘分区信息

使用 psutil.disk_partitions() 可以获取所有磁盘分区的详细信息:

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

磁盘使用情况

psutil.disk_usage() 返回特定分区的使用情况:

disk_usage = psutil.disk_usage('/')
print("根目录磁盘使用情况:")
print(f"总空间:{disk_usage.total / 1024 / 1024 / 1024:.2f} GB")
print(f"已用空间:{disk_usage.used / 1024 / 1024 / 1024:.2f} GB")
print(f"剩余空间:{disk_usage.free / 1024 / 1024 / 1024:.2f} GB")
print(f"使用率:{disk_usage.percent}%")

磁盘 IO 信息

disk_io = psutil.disk_io_counters()
print("磁盘 IO 信息:")
print(f"读操作次数:{disk_io.read_count}")
print(f"写操作次数:{disk_io.write_count}")
print(f"读取数据量:{disk_io.read_bytes / 1024 / 1024:.2f} MB")
print(f"写入数据量:{disk_io.write_bytes / 1024 / 1024:.2f} MB")

4. 获取网络信息

网络总览信息

net_io = psutil.net_io_counters()
print("网络总览信息:")
print(f"发送字节数:{net_io.bytes_sent / 1024 / 1024:.2f} MB")
print(f"接收字节数:{net_io.bytes_recv / 1024 / 1024:.2f} MB")
print(f"发送包数:{net_io.packets_sent}")
print(f"接收包数:{net_io.packets_recv}")

网络接口信息

psutil.net_if_addrs() 提供了每个网络接口的地址信息:

net_interfaces = psutil.net_if_addrs()
print("网络接口信息:")
for interface, addrs in net_interfaces.items():
    print(f"接口:{interface}")
    for addr in addrs:
        print(f"  地址:{addr.address}")
        print(f"  网络掩码:{addr.netmask}")
        print(f"  广播地址:{addr.broadcast}")
        print("-" * 20)

5. 进程管理

psutil 提供了全面的进程管理功能,可以列出所有进程,获取某个进程的详细信息,或者对进程进行操作。

获取当前运行的所有进程

for proc in psutil.process_iter(attrs=['pid', 'name', 'username']):
    print(f"PID:{proc.info['pid']},名称:{proc.info['name']},用户:{proc.info['username']}")

获取特定进程的信息

pid = 1  # 这里以 PID 为 1 的进程为例
try:
    process = psutil.Process(pid)
    print(f"进程名称:{process.name()}")
    print(f"进程状态:{process.status()}")
    print(f"CPU 使用率:{process.cpu_percent()}%")
    print(f"内存使用量:{process.memory_info().rss / 1024 / 1024:.2f} MB")
except psutil.NoSuchProcess:
    print(f"进程 PID {pid} 不存在")

终止进程

try:
    process.terminate()  # 终止进程
    print(f"进程 PID {pid} 已终止")
except psutil.NoSuchProcess:
    print(f"进程 PID {pid} 不存在")

6. 传感器信息

获取电池状态

battery = psutil.sensors_battery()
if battery:
    print(f"电量:{battery.percent}%")
    print(f"是否正在充电:{'是' if battery.power_plugged else '否'}")
else:
    print("无法获取电池信息")

总结

psutil 是一个功能丰富且易用的库,适合开发者快速获取系统信息或进行进程管理。通过本教程的示例代码,读者可以轻松上手并应用到自己的项目中。无论是构建系统监控工具,还是实现资源管理功能,psutil 都是一个值得选择的解决方案。