惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
P
Privacy International News Feed
P
Proofpoint News Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
C
CXSECURITY Database RSS Feed - CXSecurity.com
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
NISL@THU
NISL@THU
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
GbyAI
GbyAI
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Y
Y Combinator Blog
C
CERT Recently Published Vulnerability Notes
N
Netflix TechBlog - Medium
S
Security Affairs
Spread Privacy
Spread Privacy
罗磊的独立博客
腾讯CDC
MyScale Blog
MyScale Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
L
LINUX DO - 热门话题
The Cloudflare Blog
L
LangChain Blog
博客园_首页
H
Hacker News: Front Page
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
SecWiki News
SecWiki News
A
Arctic Wolf
爱范儿
爱范儿
Google Online Security Blog
Google Online Security Blog
T
Threat Research - Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
有赞技术团队
有赞技术团队
The GitHub Blog
The GitHub Blog
Cyberwarzone
Cyberwarzone
博客园 - 叶小钗
V
Visual Studio Blog
V
V2EX
T
Tailwind CSS Blog
Project Zero
Project Zero
T
The Blog of Author Tim Ferriss
F
Fortinet All Blogs
MongoDB | Blog
MongoDB | Blog
D
Docker

博客园 - 百衲本

Centos7 副本集模式部署 MongoDB centos7部署Nacos集群模式 centos7 yum快速安装clickhouse单机版 k8s高可用部署Seata kubernetes中pod磁盘占用排查 jumpserver V3 终端常用操作 Python 列表生成式、字典生成式与生成器表达式 Python 的可迭代对象、迭代器对象与生成器 python email模块自动化操作邮件 python yagmail 模块自动化操作邮件 python自动化操作PDF 国内企业邓白氏编码免费申请流程 免费公共API调用清单 Python pathlib 模块 容器网络故障排查:从 ping 到 tcpdump 的全链路思路 systemd详解 APP性能指标 Linux 上禁用 USB 存储设备 线上故障的排查清单,运维小哥拿走不谢!
Python psutil模块
百衲本 · 2025-09-17 · via 博客园 - 百衲本

一、简介

psutil(Process and System Utilities)是Python中最强大的系统监控和进程管理库之一。它提供了跨平台的系统信息获取接口,
能够轻松获取系统的CPU、内存、磁盘、网络等硬件信息,以及进程管理、系统监控等功能。无论是开发运维工具、系统监控程序,还是性能分析应用,psutil都是不可或缺的利器
该库支持Linux、Windows、macOS等主流操作系统,为开发者提供了统一的API接口,大大简化了系统编程的复杂度。

核心特性:

  • 跨平台支持:支持Linux、Windows、macOS、FreeBSD等操作系统
  • 丰富的系统信息:获取CPU、内存、磁盘、网络等硬件信息
  • 进程管理:创建、终止、监控进程及其子进程
  • 实时监控:提供实时的系统资源使用情况
  • 网络连接监控:查看网络连接状态和统计信息
  • 用户会话管理:获取当前登录用户信息
  • 高性能:底层使用C语言实现,性能优异

二、安装

pip install psutil


#验证
import psutil
print(f"psutil版本: {psutil.__version__}")
print(f"CPU核心数: {psutil.cpu_count()}")

三、基本功能

1.获取CPU信息

CPU使用率是系统监控中最重要的指标之一,psutil提供了多种方式获取CPU信息,包括总体使用率、各核心使用率、CPU频率等。通过这些信息可以实时了解系统负载情况,为性能优化提供数据支撑。

import psutil
import time

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

# 获取各核心使用率
cpu_per_core = psutil.cpu_percent(interval=1, percpu=True)
for i, usage in enumerate(cpu_per_core):
    print(f"核心{i}: {usage}%")

# 获取CPU频率信息
cpu_freq = psutil.cpu_freq()
print(f"CPU频率: {cpu_freq.current:.2f}MHz")

2.获取内存信息

psutil可以获取物理内存和虚拟内存的详细信息,包括总量、已用量、可用量等。

# 获取内存信息
memory = psutil.virtual_memory()
print(f"总内存: {memory.total / (1024**3):.2f}GB")
print(f"已用内存: {memory.used / (1024**3):.2f}GB")
print(f"内存使用率: {memory.percent}%")

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

3.获取磁盘信息

psutil能够获取各个磁盘分区的使用情况,包括总容量、已用空间、可用空间等,帮助管理员及时发现磁盘空间不足的问题。

# 获取磁盘分区信息
partitions = psutil.disk_partitions()
for partition in partitions:
    print(f"设备: {partition.device}")
    try:
        partition_usage = psutil.disk_usage(partition.mountpoint)
        print(f"  总容量: {partition_usage.total / (1024**3):.2f}GB")
        print(f"  已使用: {partition_usage.used / (1024**3):.2f}GB")
        print(f"  使用率: {partition_usage.percent}%")
    except PermissionError:
        print("  权限不足")

四、高级功能

1.进程管理与监控

psutil提供了强大的进程管理功能,可以获取系统中所有进程的详细信息,包括进程ID、名称、CPU和内存使用率、父子进程关系等。

# 获取当前进程信息
current_process = psutil.Process()
print(f"当前进程PID: {current_process.pid}")
print(f"进程名称: {current_process.name()}")
print(f"CPU使用率: {current_process.cpu_percent()}%")
print(f"内存使用: {current_process.memory_info().rss / (1024**2):.2f}MB")

# 遍历所有进程
for proc in psutil.process_iter(['pid''name''cpu_percent''memory_percent']):
    if proc.info['cpu_percent'] > 10:  # 只显示CPU使用率大于10%的进程
        print(f"PID: {proc.info['pid']}, 名称: {proc.info['name']}, "
              f"CPU: {proc.info['cpu_percent']}%, 内存: {proc.info['memory_percent']:.2f}%")

2.网络连接监控

网络监控功能可以帮助管理员了解系统的网络使用情况,包括网络接口流量统计、当前网络连接状态等。

# 获取网络接口统计信息
net_io = psutil.net_io_counters(pernic=True)
for interface, stats in net_io.items():
    print(f"接口 {interface}:")
    print(f"  发送: {stats.bytes_sent / (1024**2):.2f}MB")
    print(f"  接收: {stats.bytes_recv / (1024**2):.2f}MB")

# 获取网络连接信息
connections = psutil.net_connections()
for conn in connections[:5]:  # 只显示前5个连接
    print(f"连接: {conn.laddr} -> {conn.raddr}, 状态: {conn.status}")

五、实际应用场景

1.系统监控脚本

在实际工作中,经常需要编写系统监控脚本来实时监控服务器状态。以下是一个综合的系统监控示例,可以用于服务器健康检查和预警系统。

import psutil
import time
import smtplib
from datetime import datetime

def system_monitor():
    """系统监控函数"""
    # 设置阈值
    CPU_THRESHOLD 80
    MEMORY_THRESHOLD 85
    DISK_THRESHOLD 90
    
    # 获取系统信息
    cpu_usage = psutil.cpu_percent(interval=1)
    memory_usage = psutil.virtual_memory().percent
    disk_usage = psutil.disk_usage('/').percent
    
    # 检查是否超过阈值
    alerts = []
    if cpu_usage > CPU_THRESHOLD:
        alerts.append(f"CPU使用率过高: {cpu_usage}%")
    if memory_usage > MEMORY_THRESHOLD:
        alerts.append(f"内存使用率过高: {memory_usage}%")
    if disk_usage > DISK_THRESHOLD:
        alerts.append(f"磁盘使用率过高: {disk_usage}%")
    
    # 记录日志
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_info = f"[{timestamp}] CPU: {cpu_usage}%, 内存: {memory_usage}%, 磁盘: {disk_usage}%"
    print(log_info)
    
    if alerts:
        print("警告:""; ".join(alerts))
    
    return alerts

# 持续监控
whileTrue:
    system_monitor()
    time.sleep(60)  # 每分钟检查一次

2.进程管理工具

在多进程应用中,需要监控和管理子进程的状态。以下示例展示了如何使用psutil来监控特定进程的资源使用情况,并在必要时进行进程管理操作。

def monitor_process_by_name(process_name):
    """根据进程名监控进程"""
    for proc in psutil.process_iter(['pid''name''cpu_percent''memory_info']):
        if process_name.lower() in proc.info['name'].lower():
            memory_mb = proc.info['memory_info'].rss / (1024**2)
            print(f"进程: {proc.info['name']}")
            print(f"PID: {proc.info['pid']}")
            print(f"CPU: {proc.info['cpu_percent']}%")
            print(f"内存: {memory_mb:.2f}MB")
            
            # 如果内存使用超过1GB,发出警告
            if memory_mb > 1024:
                print("警告:该进程内存使用过高!")

# 监控Python进程
monitor_process_by_name("python")

总结

psutil作为Python生态系统中最优秀的系统监控库,为开发者提供了全面而强大的系统信息获取和进程管理功能。通过本文的介绍,我们了解了psutil的核心特性、基本使用方法以及高级功能应用。无论是简单的系统信息查询,还是复杂的服务器监控系统开发,psutil都能胜任。其跨平台的特性使得代码具有良好的可移植性,统一的API接口大大降低了学习成本。在实际项目中,合理运用psutil可以帮助我们构建高效的监控系统、性能分析工具和自动化运维脚本,显著提升系统管理的效率和质量。

Github地址:https://github.com/giampaolo/psutil

抄自于:https://mp.weixin.qq.com/s/6AA4_4x2R9CPXuxcIRKFhQ