Python 之 psutil 模块使用详解

CPU信息

cpu_times

使用 cpu_times 方法获取 cpu 的完整信息(不同类型机器上调用的结果参数会有稍许差异)。

  • ‌**user**‌: CPU在用户模式下执行进程所花费的时间。
  • ‌**nice**‌: CPU在低优先级(nice)用户模式下执行进程所花费的时间。
  • ‌**system**‌: CPU在系统(内核)模式下执行进程所花费的时间。
  • ‌**idle**‌: CPU处于空闲状态的时间,即没有执行任何任务的时间。‌‌
  • ‌**iowait**‌: CPU等待I/O操作完成(如磁盘读写)所花费的时间。
  • ‌**irq**‌: CPU处理硬件中断所花费的时间。硬件中断通常由外部设备(如键盘、网络接口)触发。‌‌
  • ‌**softirq**‌: CPU处理软件中断所花费的时间。软件中断由内核软件事件触发,用于处理延迟的任务。‌‌
  • ‌**steal**‌: 在虚拟化环境中,CPU被其他操作系统(如其他虚拟机)占用的时间。
  • ‌**guest**‌: CPU运行虚拟CPU(guest OS)所花费的时间,当Linux内核作为虚拟机管理器时使用。‌‌
  • ‌**guest_nice**‌: CPU运行低优先级虚拟CPU(guest OS)所花费的时间。
  • interupt: 中断处理时间。‌‌
  • dpc: 延迟过程调用时间。‌‌
python 复制代码
import psutil

cpu_times = psutil.cpu_times()
print(cpu_times)
# scputimes(user=14278.062499999998, system=11435.796875000466, idle=3410064.6406249995, interrupt=549.78125, dpc=259.203125)

cpu_count

获取 cpu 逻辑和物理个数

python 复制代码
import psutil

# cpu 逻辑核数
print(psutil.cpu_count())  # 8
# cpu 物理核数
print(psutil.cpu_count(logical=False))  # 4

cpu_percent

获取 cpu 指定间隔内的平均使用率

python 复制代码
import psutil

# 返回系统在过去指定时间间隔内的平均 CPU 使用率
print(psutil.cpu_percent(2))  # 3.0
# 返回系统每个核心在过去指定时间间隔内的平均 CPU 使用率
print(psutil.cpu_percent(2, percpu=True))  # [4.6, 0.8, 5.5, 0.0, 0.0, 7.8, 0.8, 10.2]

cpu_freq

获取 cpu 当前频率

python 复制代码
import psutil

cpu_freq = psutil.cpu_freq()
print(cpu_freq)
# scpufreq(current=2419.0, min=0.0, max=2419.0)
print(f"%.2fMHz" % (cpu_freq[0]))
# 2419.00MHz
print(f"%.2fGHz" % (int(cpu_freq[0])/1000.0))
# 2.42GHz

cpu_stats

返回 CPU 相关的统计信息

  • ctx_switches - 上下文切换次数

  • interrupts - 硬件中断次数

  • soft_interrupts - 软中断次数

  • syscalls - 系统调用次数

python 复制代码
import psutil

stats = psutil.cpu_stats()
print(stats)
# scpustats(ctx_switches=553719524, interrupts=384088765, soft_interrupts=0, syscalls=4068156150)

print("=== CPU 统计信息 ===")
print(f"上下文切换次数:\t{stats.ctx_switches:,}")
print(f"硬件中断次数:  \t{stats.interrupts:,}")
print(f"软中断次数:   \t{stats.soft_interrupts:,}")
print(f"系统调用次数: \t{stats.syscalls:,}")
# === CPU 统计信息 ===
# 上下文切换次数:	552,885,119
# 硬件中断次数:  	383,491,459
# 软中断次数:   	0
# 系统调用次数: 	4,063,556,700

磁盘信息

python 复制代码
import psutil

disk_usage = psutil.disk_usage("./tmp")
print(disk_usage)
# sdiskusage(total=201346846720, used=30457720832, free=170889125888, percent=15.1)
total = disk_usage.total / 1024 / 1024 / 1024
used = disk_usage.used / 1024 / 1024 / 1024
free = disk_usage.free / 1024 / 1024 / 1024

print("total: {:.2f}G".format(total))  # total: 187.52G
print("used: {:.2f}G".format(used))  # used: 28.37G
print("free: {:.2f}G".format(free))  # free: 159.15G
print("percent: {:.2f}%".format(disk_usage.percent))  # percent: 15.10%

至于获取磁盘信息,其实新版 Python 的标准库中的 shutil 模块也有相应的实现。

python 复制代码
import shutil

disk_usage = shutil.disk_usage("./tmp")
print(disk_usage)
# usage(total=201346846720, used=30460338176, free=170886508544)
total = disk_usage.total / 1024 / 1024 / 1024
used = disk_usage.used / 1024 / 1024 / 1024
free = disk_usage.free / 1024 / 1024 / 1024

print("total: {:.2f}G".format(total))  # total: 187.52G
print("used: {:.2f}G".format(used))  # used: 28.37G
print("free: {:.2f}G".format(free))  # free: 159.15G

内存信息

python 复制代码
import psutil

memory = psutil.virtual_memory()
print(memory)
# svmem(total=8254660608, available=1150599168, percent=86.1, used=7104061440, free=1150599168)
print(f"总计:%.2fG" % (memory.total / 1024 /1024 / 1024))
print(f"已使用:%.2fG" % (memory.used / 1024 /1024 / 1024))
print(f"使用率:%.2f%%" % memory.percent)
print(f"可用:%.2fG" % (memory.available / 1024 /1024 / 1024))
print(f"空闲:%.2fG" % (memory.free / 1024 /1024 / 1024))
# 总计:7.69G
# 已使用:6.62G
# 使用率:86.10%
# 可用:1.07G
# 空闲:1.07G

网络信息

python 复制代码
import psutil


def format_bytes(bytes_num):
    """格式化字节数为易读单位"""
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if bytes_num < 1024.0:
            return f"{bytes_num:.2f} {unit}"
        bytes_num /= 1024.0
    return f"{bytes_num:.2f} PB"


def format_speed(bytes_per_sec):
    """格式化速度"""
    if bytes_per_sec < 1024:
        return f"{bytes_per_sec:.1f} B/s"
    elif bytes_per_sec < 1024 * 1024:
        return f"{bytes_per_sec / 1024:.1f} KB/s"
    else:
        return f"{bytes_per_sec / (1024 * 1024):.1f} MB/s"


def display_net_io_summary():
    """显示网络I/O摘要"""
    net_io = psutil.net_io_counters()
    print(net_io)
    # snetio(bytes_sent=158940220, bytes_recv=1463139590, packets_sent=769447, packets_recv=781501, errin=0, errout=21, dropin=0, dropout=0)

    print("=== 网络I/O统计 ===")
    print(f"发送: {format_bytes(net_io.bytes_sent)}")
    print(f"接收: {format_bytes(net_io.bytes_recv)}")
    print(f"发送包: {net_io.packets_sent:,}")
    print(f"接收包: {net_io.packets_recv:,}")

    if net_io.errin > 0 or net_io.errout > 0:
        print(f"接收错误: {net_io.errin}")
        print(f"发送错误: {net_io.errout}")

    if net_io.dropin > 0 or net_io.dropout > 0:
        print(f"接收丢弃: {net_io.dropin}")
        print(f"发送丢弃: {net_io.dropout}")
    
    # === 网络I/O统计 ===
    # 发送: 151.58 MB
    # 接收: 1.36 GB
    # 发送包: 769,447
    # 接收包: 781,501
    # 接收错误: 0
    # 发送错误: 21


display_net_io_summary()

开机时间

python 复制代码
import psutil
import datetime

boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
print(boot_time)  # 2025-12-05 16:24:20

进程信息

获取所有进程的进程号

python 复制代码
import psutil

print(psutil.pids())
# [0, 4, 72, 132, 408, 460, 712, 808, 824, 828, 880, 900, 908, 980, 992, 1032, 1040, 1080, 1108, 1176, ...]

进程存在性判断

python 复制代码
import psutil

print(psutil.pid_exists(10564))  # True
print(psutil.pid_exists(1050))  # False

进程详情

python 复制代码
import psutil

p = psutil.Process(10564)
print(p.name())  # 进程名
print(p.exe())  # 进程的bin路径
print(p.cwd())  # 进程的工作目录绝对路径
print(p.status())  # 进程状态
print(p.create_time())  # 进程创建时间
# p.uids()  # 进程uid信息
# p.gids()  # 进程的gid信息
print(p.cpu_times())  # 进程的cpu时间信息,包括user,system两个cpu信息
print(p.cpu_affinity())  # get进程cpu亲和度
print(p.memory_percent())  # 进程内存利用率
print(p.memory_info())  # 进程内存rss,vms信息
print(p.io_counters())  # 进程的IO信息,包括读写IO数字及参数
# p.connectios()  # 返回进程列表
print(p.num_threads())  # 进程开启的线程数

# svchost.exe
# C:\Windows\System32\svchost.exe
# C:\Windows\system32
# running
# 1765192686.9710388
# pcputimes(user=1.625, system=1.5625, children_user=0.0, children_system=0.0)
# [0, 1, 2, 3, 4, 5, 6, 7]
# 0.18458808573223415
# pmem(rss=15237120, vms=2764800, num_page_faults=16585, peak_wset=15474688, wset=15237120, peak_paged_pool=99696, paged_pool=99680, peak_nonpaged_pool=14864, nonpaged_pool=13232, pagefile=2764800, peak_pagefile=3178496, private=2764800)
# pio(read_count=1, write_count=0, read_bytes=4524, write_bytes=0, other_count=183, other_bytes=2012)
# 4

硬件信息

电源信息

python 复制代码
import psutil

# 电池信息
battery = psutil.sensors_battery()
print(battery)
# sbattery(percent=97, secsleft=20018, power_plugged=False)
print("电池剩余电量:{:.2f}%".format(battery.percent))
# 电池剩余电量:97.00%
print("电量可用时长:{:.2f}h".format(battery.secsleft / 60 / 60))
# 电量可用时长:5.56h
print("电源是否接入:{:}".format(battery.power_plugged))
# 电源是否接入:False

风扇信息

python 复制代码
import psutil

# 风扇和温度信息一般在 Linux 的物理机上才可以获取到
fans = psutil.sensors_fans()
print(fans)

温度信息

python 复制代码
import psutil

# 风扇和温度信息一般在 Linux 的物理机上才可以获取到
temperatures = psutil.sensors_temperatures()
print(temperatures)
相关推荐
free-elcmacom2 小时前
机器学习进阶<6>神奇的披萨店与学区房:走进RBFN的直觉世界
人工智能·python·机器学习·rbfn
free-elcmacom2 小时前
机器学习进阶<7>人脸识别特征锚点Python实现
人工智能·python·机器学习·rbfn
天才少女爱迪生2 小时前
图像序列预测有什么算法方案
人工智能·python·深度学习·算法
计算机学姐2 小时前
基于Python的高校后勤报修系统【2026最新】
开发语言·vue.js·后端·python·mysql·django·flask
Q_Q19632884752 小时前
python+django/flask+vue的智能房价分析与预测系统
spring boot·python·django·flask·node.js·php
txwtech2 小时前
第20篇 python如何找到pyd文件的
开发语言·python
00后程序员张2 小时前
Python 抓包工具全面解析,从网络监听、协议解析到底层数据流捕获的多层调试方案
开发语言·网络·python·ios·小程序·uni-app·iphone
胡八一2 小时前
解决使用PCbuild\build.bat构建python之后,运行pip报错
开发语言·python·pip
Freshman小白2 小时前
《科技信息检索与论文写作专题讲座》网课答案
python·科技·网课答案