1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import psutil
mem = psutil.virtual_memory() print("🔹 内存信息") print(f"总内存: {round(mem.total / (1024**3), 2)} GB") print(f"已使用: {round(mem.used / (1024**3), 2)} GB") print(f"可用: {round(mem.available / (1024**3), 2)} GB") print(f"使用率: {mem.percent}%") print()
disk = psutil.disk_usage('/') print("🔹 磁盘信息 (/ 分区)") print(f"总容量: {round(disk.total / (1024**3), 2)} GB") print(f"已使用: {round(disk.used / (1024**3), 2)} GB") print(f"可用: {round(disk.free / (1024**3), 2)} GB") print(f"使用率: {disk.percent}%") print()
print("🔹 CPU 信息") print(f"CPU 总核数(逻辑核): {psutil.cpu_count(logical=True)}") print(f"CPU 总核数(物理核): {psutil.cpu_count(logical=False)}")
cpu_percent_total = psutil.cpu_percent(interval=1) print(f"CPU 当前总使用率: {cpu_percent_total:2f}%")
import psutil
cpu_per_core = psutil.cpu_percent(interval=1, percpu=True) print(type(cpu_per_core)) print(cpu_per_core) for i, percent in enumerate(cpu_per_core): print(f"CPU 核心 {i}: {percent}%")
|
🧠 模块作用
psutil(process and system utilities)用于获取系统运行的进程信息、CPU、内存、磁盘、网络等资源的使用情况,广泛用于监控脚本和性能分析。
| 功能 |
代码示例 |
说明 |
| 查看 CPU 信息 |
psutil.cpu_percent() |
获取 CPU 使用率(默认是瞬时值) |
| 多核 CPU |
psutil.cpu_percent(percpu=True) |
获取每个 CPU 的使用率 |
| CPU 核心数 |
psutil.cpu_count(logical=False) |
获取物理核心数 |
| 内存信息 |
psutil.virtual_memory() |
返回内存总量、已用、剩余等 |
| 交换内存 |
psutil.swap_memory() |
获取交换分区使用情况 |
| 磁盘使用 |
psutil.disk_usage(‘/‘) |
获取某个挂载点的磁盘使用情况 |
| 磁盘 IO |
psutil.disk_io_counters() |
读取/写入字节数与次数 |
| 网络 IO |
psutil.net_io_counters() |
网络传输字节和包数 |
| 网络接口 |
psutil.net_if_addrs() |
获取每个网络接口的 IP 等信息 |
| 当前进程 |
psutil.Process() |
获取当前进程的 CPU/内存等信息 |
| 所有进程 |
psutil.pids() / psutil.process_iter() |
遍历所有 PID 并查看进程状态 |