模块介绍

psutil 是一个 Python 的跨平台库,用于获取系统和进程的运行状态以及实时信息。它能够方便地访问系统的 CPU、内存、磁盘、网络等资源的使用情况。此外,psutil 也能够管理和监控进程,非常适合用于系统监控和性能分析等应用。psutil 库适用于 Python 3.x 版本,自版本 5.0.0 起更为稳定,因此推荐使用最新版本的 Python。

应用场景

psutil 库的主要用途是系统监控和资源管理。以下是一些具体应用场景:

  • 系统性能监控:可以用来实时监控系统的 CPU 负荷、内存使用情况、磁盘 I/O 等。
  • 进程管理:能获取当前运行进程的信息,例如内存占用、CPU 时间等,也可以结束某个进程。
  • 网络监控:监控系统的网络连接和流量,分析网络性能。
  • 开发与测试助手:在开发应用时,可以用来进行资源的调试与优化。

安装说明

psutil 库并不是 Python 的内置模块,需要额外安装。可以使用以下命令进行安装:

pip install psutil  # 使用pip安装psutil库
  • 1.

安装完成后,即可在 Python 项目中使用该模块。

用法举例

1. 获取 CPU 信息
import psutil  # 导入psutil库

# 获取CPU的逻辑核心数
cpu_cores = psutil.cpu_count(logical=True)  # 获取逻辑核心数
print(f"逻辑核心数: {cpu_cores}")  # 输出逻辑核心数量

# 获取CPU的使用率
cpu_usage = psutil.cpu_percent(interval=1)  # 获取当前CPU使用率,时间间隔1秒
print(f"CPU使用率: {cpu_usage}%")  # 输出CPU使用率
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

 

2. 获取内存信息场景说明:上述代码获取系统的 CPU 核心数量以及当前的 CPU 使用率,可以用于监控服务器性能。

import psutil  # 导入psutil库

# 获取虚拟内存信息
memory_info = psutil.virtual_memory()  # 获取内存信息
print(f"总内存: {memory_info.total / (1024 ** 3):.2f} GB")  # 输出总内存
print(f"可用内存: {memory_info.available / (1024 ** 3):.2f} GB")  # 输出可用内存
print(f"内存使用率: {memory_info.percent}%")  # 输出内存使用率
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

 

3. 监控网络流量场景说明:此代码帮助开发者监控系统内存的使用情况,确保内存充足以支持应用程序的运行。

import psutil  # 导入psutil库

# 获取网络I/O信息
net_io = psutil.net_io_counters()  # 获取网络I/O信息
print(f"发送字节数: {net_io.bytes_sent} bytes")  # 输出网络发送的字节数
print(f"接收字节数: {net_io.bytes_recv} bytes")  # 输出网络接收的字节数
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

 场景说明:该示例代码用于监控网络流量,非常适合用于数据流量分析和带宽监控等场景。

 

4. 获取磁盘相关信息

import psutil
partitions = psutil.disk_partitions()
print("磁盘分区信息:", partitions)


usage = psutil.disk_usage('/')
print("磁盘使用情况:", usage)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

 

5.获取传感器信息

import psutil
sensors_temperatures = psutil.sensors_temperatures()
print("传感器信息:", sensors_temperatures)
  • 1.
  • 2.
  • 3.

 

6.进程管理

import psutil

# 获取正在运行的进程
for process in psutil.process_iter():
    print(process.name())


# 获取指定进程的详细信息
process_id = 1234
process = psutil.Process(process_id)
print(process.name())
print(process.cpu_percent(interval=1))
print(process.memory_info().rss)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

 

 


 

示例:

1.监控设备信息

import time
import psutil
while True:
    cpu_usage = psutil.cpu_percent(interval=1)
    memory_usage = psutil.virtual_memory().percent
    disk_usage = psutil.disk_usage('/').percent
    network_usage = psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv
    print("CPU使用率:", cpu_usage)
    print("内存使用率:", memory_usage)
    print("磁盘使用率:", disk_usage)
    print("网络使用量:", network_usage)
    time.sleep(1)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

 

 

 

 

相关文档: