Psutil模块

Psutil模块

一、模块介绍

psutil(Process and System Utilities)模块用于在Python中获取进程和系统利用率(例如CPU、内存、磁盘、网络等)的信息。主要用于系统监控、分析和限制系统资源及管理正在运行的进程。

二、模块下载

pip install psutil

三、模块导入

import psutil

四、模块函数

1.psutil.cpu_percent()

作用

  获取CPU的使用率。

语法

psutil.cpu_percent(interval=None, percpu=False)

参数

  • interval:浮点数,表示测量CPU使用率的时间间隔(以秒为单位)。如果不指定,则返回自上次调用cpu_percent()或系统启动以来的平均CPU使用率(如果没有先前的调用,则返回0.0)
  • percpu:布尔值,默认为False。如果设置为True,则函数返回一个包含所有逻辑CPU使用率的列表,而不是整个系统的总CPU使用率

示例

  • 获取当前总的CPU使用率
import psutil

# 获取总的CPU使用率
print(psutil.cpu_percent())  # 0.0
  • 获取指定时间间隔内的平均CPU使用率
import psutil

# 获取1秒内的平均CPU使用率
print(psutil.cpu_percent(interval=1))  # 1.6
  • 获取每个CPU核心的使用率
import psutil

# 获取每个CPU核心的使用率
per_cpu_percentages = psutil.cpu_percent(percpu=True, interval=1)
for i, percent in enumerate(per_cpu_percentages):
    print(f"Core {i}: {percent}%")

结果

Core 0: 3.1%
Core 1: 1.6%
Core 2: 0.0%
Core 3: 1.6%
Core 4: 1.6%
Core 5: 0.0%
Core 6: 0.0%
Core 7: 1.6%
Core 8: 0.0%
Core 9: 0.0%
Core 10: 3.1%
Core 11: 0.0%
Core 12: 0.0%
Core 13: 0.0%
Core 14: 0.0%
Core 15: 1.6%
  • 持续监控CPU使用率
import psutil

# 持续监控CPU使用率,每2秒打印一次
try:
    for i in range(5):
        print(psutil.cpu_percent(interval=2))
except KeyboardInterrupt:
    pass

结果

1.1
1.1
0.3
0.7
1.1

2.psutil.cpu_count()

作用

  用于获取当前系统上的CPU数量。

语法

psutil.cpu_count([logical=False])

参数

  • logical:布尔值,默认为False。如果为True,则返回逻辑CPU的数量(包括超线程),否则返回物理CPU的数量

示例

import psutil

# 获取逻辑CPU的数量(包括超线程)
logical_cpu_count = psutil.cpu_count(logical=True)
print(f"Logical CPU count: {logical_cpu_count}")

# 获取物理CPU的数量
physical_cpu_count = psutil.cpu_count(logical=False)
print(f"Physical CPU count: {physical_cpu_count}")

结果

Logical CPU count: 16
Physical CPU count: 8

3.psutil.cpu_times()

作用

  获取系统CPU的运行时间统计信息。

语法

psutil.cpu_times(percpu=False)

参数

  • percpu:布尔值,默认为False。如果为True,则返回一个列表,其中包含每个CPU核心的运行时间统计信息,否则返回总的运行时间统计信息。

返回值

返回一个元组,包含以下字段:

  • user:用户模式下消耗的CPU时间(秒)
  • system:系统模式下消耗的CPU时间(秒)
  • idle:空闲模式下消耗的CPU时间(秒)
  • nice:(UNIX)低优先级进程消耗的CPU时间(秒)
  • iowait:(Linux)等待I/O操作的CPU时间(秒)
  • irq:(Linux, FreeBSD)处理硬件中断的CPU时间(秒)
  • softirq:(Linux)处理软件中断的CPU时间(秒)
  • steal:(Linux 2.6.11+)虚拟化环境中运行其他操作系统时被偷走的CPU时间(秒)
  • guest:(Linux 2.6.24+)在运行虚拟CPU时消耗的CPU时间(秒)
  • guest_nice:(Linux 3.2.0+)以低优先级运行虚拟CPU时消耗的CPU时间(秒)

示例

import psutil

# 获取总的CPU运行时间统计信息
total_times = psutil.cpu_times()
print(f"Total CPU times: {total_times}")

# 获取每个CPU核心的运行时间统计信息
percpu_times = psutil.cpu_times(percpu=True)
for i, times in enumerate(percpu_times):
    print(f"CPU core {i}: {times}")

结果

Total CPU times: scputimes(user=3398.296875, system=5713.078125000058, idle=324484.60937499994, interrupt=115.875, dpc=103.484375)
CPU core 0: scputimes(user=208.515625, system=1076.0, idle=19566.328125, interrupt=83.5, dpc=83.640625)
CPU core 1: scputimes(user=112.125, system=181.40625, idle=20556.1875, interrupt=2.65625, dpc=2.328125)
CPU core 2: scputimes(user=535.359375, system=790.171875, idle=19524.171875, interrupt=5.453125, dpc=2.59375)
CPU core 3: scputimes(user=134.65625, system=200.703125, idle=20514.34375, interrupt=1.15625, dpc=0.96875)
CPU core 4: scputimes(user=243.46875, system=435.296875, idle=20170.9375, interrupt=2.8125, dpc=1.515625)
CPU core 5: scputimes(user=158.84375, system=200.484375, idle=20490.359375, interrupt=1.828125, dpc=1.21875)
CPU core 6: scputimes(user=307.125, system=299.171875, idle=20243.390625, interrupt=2.203125, dpc=1.171875)
CPU core 7: scputimes(user=234.25, system=323.5625, idle=20291.875, interrupt=1.5625, dpc=1.40625)
CPU core 8: scputimes(user=178.6875, system=276.0625, idle=20394.921875, interrupt=2.125, dpc=0.90625)
CPU core 9: scputimes(user=141.5625, system=268.359375, idle=20439.75, interrupt=1.5625, dpc=1.125)
CPU core 10: scputimes(user=272.078125, system=326.84375, idle=20250.734375, interrupt=2.03125, dpc=1.4375)
CPU core 11: scputimes(user=195.796875, system=245.890625, idle=20407.96875, interrupt=1.234375, dpc=0.9375)
CPU core 12: scputimes(user=164.984375, system=273.96875, idle=20410.703125, interrupt=2.125, dpc=1.046875)
CPU core 13: scputimes(user=118.859375, system=198.609375, idle=20532.1875, interrupt=1.9375, dpc=1.09375)
CPU core 14: scputimes(user=232.953125, system=275.8125, idle=20340.875, interrupt=2.28125, dpc=0.953125)
CPU core 15: scputimes(user=159.03125, system=340.734375, idle=20349.875, interrupt=1.40625, dpc=1.140625)

4.psutil.swap_memory()

作用

  获取系统交换内存(swap)的使用情况。

语法

psutil.swap_memory()

返回值

返回值一个命名元组,包含以下字段:

  • total:交换内存总量,单位为字节(Byte)
  • used:已使用的交换内存量,单位为字节(Byte)
  • free:空闲的交换内存量,单位为字节(Byte)
  • percent:使用的交换内存占总量的百分比,单位为百分比(%)
  • sin:从磁盘交换到内存的数据量,单位为字节(Byte)
  • sout:从内存交换到磁盘的数据量,单位为字节(Byte)

示例

import psutil

# 获取系统交换内存的使用情况
swap_memory = psutil.swap_memory()

print(f"Total swap memory: {swap_memory.total / (1024 ** 2):.2f} MiB")
print(f"Used swap memory: {swap_memory.used / (1024 ** 2):.2f} MiB")
print(f"Free swap memory: {swap_memory.free / (1024 ** 2):.2f} MiB")
print(f"Swap memory usage: {swap_memory.percent:.2f}%")
print(f"Data swapped in from disk: {swap_memory.sin / (1024 ** 2):.2f} MiB")
print(f"Data swapped out to disk: {swap_memory.sout / (1024 ** 2):.2f} MiB")

结果

Total swap memory: 14848.00 MiB
Used swap memory: 78.57 MiB
Free swap memory: 14769.43 MiB
Swap memory usage: 0.50%
Data swapped in from disk: 0.00 MiB
Data swapped out to disk: 0.00 MiB

5.psutil.virtual_memory()

作用

  获取系统内存的统计信息

语法

psutil.virtual_memory()

返回值

返回一个元组,包含以下字段:

  • total:总物理内存(字节)
  • available:可用于启动新应用程序的内存,这等于free + buffers + cached(字节)
  • percent:内存使用率百分比
  • used:使用的内存量(字节),等于total - free
  • free:未使用的内存量(字节)
  • active:(Linux/BSD)活跃内存量(字节)
  • inactive:(Linux/BSD)非活跃内存量(字节)
  • buffers:(Linux/BSD)缓冲区内存量(字节)
  • cached:(Linux/Windows)缓存内存量(字节)
  • shared:(Linux/Windows)共享内存量(字节)
  • slab:(Linux)内核数据结构缓存(字节)

示例

import psutil

# 获取内存使用情况
mem = psutil.virtual_memory()

# 打印内存使用情况
print(f"Total: {mem.total / (1024 ** 3):.2f} GB")
print(f"Available: {mem.available / (1024 ** 3):.2f} GB")
print(f"Used: {mem.used / (1024 ** 3):.2f} GB")
print(f"Free: {mem.free / (1024 ** 3):.2f} GB")
print(f"Percentage: {mem.percent}%")

# 打印其他内存统计信息(如果存在)
if hasattr(mem, 'active'):
    print(f"Active: {mem.active / (1024 ** 3):.2f} GB")
if hasattr(mem, 'inactive'):
    print(f"Inactive: {mem.inactive / (1024 ** 3):.2f} GB")
if hasattr(mem, 'buffers'):
    print(f"Buffers: {mem.buffers / (1024 ** 3):.2f} GB")
if hasattr(mem, 'cached'):
    print(f"Cached: {mem.cached / (1024 ** 3):.2f} GB")
if hasattr(mem, 'shared'):
    print(f"Shared: {mem.shared / (1024 ** 3):.2f} GB")
if hasattr(mem, 'slab'):
    print(f"Slab: {mem.slab / (1024 ** 3):.2f} GB")

结果

Total: 15.84 GB
Available: 4.98 GB
Used: 10.86 GB
Free: 4.98 GB
Percentage: 68.6%

6.psutil.disk_usage()

作用

  获取磁盘分区的使用情况。

语法

psutil.disk_usage(path)

参数

  • path:要获取使用情况的磁盘分区的路径。如果是/,它将返回整个文件系统的使用情况

返回值

返回一个命名元组,包含了关于磁盘使用情况的多个字段:

  • total:磁盘总容量(字节)
  • used:已使用的磁盘空间(字节)
  • free:未使用的磁盘空间(字节)
  • percent:磁盘使用率百分比

示例

import psutil

# 获取指定路径的磁盘使用情况
# 这里以 '/' 表示整个文件系统
disk_usage = psutil.disk_usage('/')

# 打印磁盘使用情况
print(f"Total: {disk_usage.total / (1024 ** 3):.2f} GB")
print(f"Used: {disk_usage.used / (1024 ** 3):.2f} GB")
print(f"Free: {disk_usage.free / (1024 ** 3):.2f} GB")
print(f"Percentage: {disk_usage.percent}%")

结果

Total: 375.94 GB
Used: 177.20 GB
Free: 198.74 GB
Percentage: 47.1%

7.psutil.disk_partitions()

作用

  获取磁盘分区信息。

语法

psutil.disk_partitions(all=False)

参数

  • all:布尔值,默认为False。当设置为True时,会返回所有分区,包括伪和重复的分区。当设置为False时,只会返回物理设备上的分区。

返回值
返回值一个列表,列表中的每个元素都是一个命名元组,包含关于每个磁盘分区的信息:

  • device:分区的设备路径
  • mountpoint:分区的挂载点
  • fstype:文件系统类型
  • opts:分区的挂载选项(以逗号分隔的字符串)

示例

import psutil

# 获取磁盘分区信息
partitions = psutil.disk_partitions()

# 打印每个分区的详细信息
for partition in partitions:
    print(f"Device: {partition.device}")
    print(f"Mountpoint: {partition.mountpoint}")
    print(f"File system type: {partition.fstype}")
    print(f"Mount options: {partition.opts}")
    print("-" * 40)

结果

Device: C:\
Mountpoint: C:\
File system type: NTFS
Mount options: rw,fixed
----------------------------------------
Device: D:\
Mountpoint: D:\
File system type: NTFS
Mount options: rw,fixed
----------------------------------------

8.psutil.disk_io_counters()

作用

  返回系统磁盘I/O统计信息。

语法

psutil.disk_io_counters(perdisk=False, nowrap=True)

参数

  • perdisk:布尔值,默认为False,当设置为True时,返回每个磁盘的I/O统计信息,而不是整个系统的总计
  • nowrap:布尔值,默认为True,当设置为False时,返回的统计信息不会自动重置,允许调用者手动计算差值

返回值:

perdiskFalse时,返回一个命名元组,包含整个系统的磁盘I/O统计信息:

  • read_count:读取操作的次数
  • write_count:写入操作的次数
  • read_bytes:读取的字节数
  • write_bytes:写入的字节数
  • read_time:读取操作花费的时间(以毫秒为单位)
  • write_time:写入操作花费的时间(以毫秒为单位)
  • read_merged_count:合并读取操作的次数
  • write_merged_count:合并写入操作的次数
  • busy_time:磁盘忙于处理I/O请求的时间(以毫秒为单位)

perdiskTrue时,返回一个字典,其中键是磁盘名称,值是命名元组,包含每个磁盘的I/O统计信息。

示例

import psutil

# 获取整个系统的磁盘I/O统计信息
total_disk_io = psutil.disk_io_counters()
print(f"Total read bytes: {total_disk_io.read_bytes}")
print(f"Total write bytes: {total_disk_io.write_bytes}")

# 获取每个磁盘的I/O统计信息
per_disk_io = psutil.disk_io_counters(perdisk=True)
for disk, disk_io in per_disk_io.items():
    print(f"Disk: {disk}")
    print(f"Read bytes: {disk_io.read_bytes}")
    print(f"Write bytes: {disk_io.write_bytes}")
    print(f"Read count: {disk_io.read_count}")
    print(f"Write count: {disk_io.write_count}")
    print("-" * 40)

结果

Total read bytes: 22825603584
Total write bytes: 91158664192
Disk: PhysicalDrive0
Read bytes: 22825603584
Write bytes: 91158664192
Read count: 579001
Write count: 1036339
----------------------------------------

9.psutil.net_io_counters()

作用

  返回系统网络I/O统计信息。

语法

psutil.net_io_counters(pernic=False, nowrap=True)

参数

  • pernic:布尔值,默认为False。当设置为True时,返回每个网络接口的I/O统计信息,而不是整个系统的总计
  • nowrap:布尔值,默认为True。当设置为False时,返回的统计信息不会自动重置,允许调用者手动计算差值

返回值
pernicFalse时,返回一个命名元组,包含整个系统的网络I/O统计信息:

  • bytes_sent:发送的字节数
  • bytes_recv:接收的字节数
  • packets_sent:发送的包数
  • packets_recv:接收的包数
  • errin:接收时发生的错误数
  • errout:发送时发生的错误数
  • dropin:接收时丢弃的包数
  • dropout:发送时丢弃的包数

pernicTrue时,返回一个字典,其中键是网络接口名称,值是命名元组,包含每个网络接口的I/O统计信息。

示例

import psutil

# 获取整个系统的网络I/O统计信息
total_net_io = psutil.net_io_counters()
print(f"Total bytes sent: {total_net_io.bytes_sent}")
print(f"Total bytes received: {total_net_io.bytes_recv}")

# 获取每个网络接口的网络I/O统计信息
per_nic_io = psutil.net_io_counters(pernic=True)
for nic, nic_io in per_nic_io.items():
    print(f"Interface: {nic}")
    print(f"Bytes sent: {nic_io.bytes_sent}")
    print(f"Bytes received: {nic_io.bytes_recv}")
    print(f"Packets sent: {nic_io.packets_sent}")
    print(f"Packets received: {nic_io.packets_recv}")
    print(f"Errors in: {nic_io.errin}")
    print(f"Errors out: {nic_io.errout}")
    print(f"Dropped in: {nic_io.dropin}")
    print(f"Dropped out: {nic_io.dropout}")
    print("-" * 40)

结果

Total bytes sent: 295664161
Total bytes received: 26581061288
Interface: 本地连接
Bytes sent: 0
Bytes received: 0
Packets sent: 0
Packets received: 0
Errors in: 0
Errors out: 0
Dropped in: 0
Dropped out: 0
----------------------------------------
Interface: 本地连接* 1
Bytes sent: 0
Bytes received: 0
Packets sent: 0
Packets received: 0
Errors in: 0
Errors out: 0
Dropped in: 0
Dropped out: 0
----------------------------------------
Interface: 本地连接* 2
Bytes sent: 0
Bytes received: 0
Packets sent: 0
Packets received: 0
Errors in: 0
Errors out: 0
Dropped in: 0
Dropped out: 0
----------------------------------------
Interface: VMware Network Adapter VMnet1
Bytes sent: 1941
Bytes received: 45
Packets sent: 1940
Packets received: 45
Errors in: 0
Errors out: 0
Dropped in: 0
Dropped out: 0
----------------------------------------
Interface: VMware Network Adapter VMnet8
Bytes sent: 6897
Bytes received: 45
Packets sent: 6895
Packets received: 45
Errors in: 0
Errors out: 0
Dropped in: 0
Dropped out: 0
----------------------------------------
Interface: WLAN
Bytes sent: 295655323
Bytes received: 26581061198
Packets sent: 2074840
Packets received: 18728308
Errors in: 0
Errors out: 0
Dropped in: 0
Dropped out: 0
----------------------------------------
Interface: 以太网 2
Bytes sent: 0
Bytes received: 0
Packets sent: 0
Packets received: 0
Errors in: 0
Errors out: 0
Dropped in: 0
Dropped out: 0
----------------------------------------
Interface: Loopback Pseudo-Interface 1
Bytes sent: 0
Bytes received: 0
Packets sent: 0
Packets received: 0
Errors in: 0
Errors out: 0
Dropped in: 0
Dropped out: 0
----------------------------------------

10.psutil.net_if_addrs()

作用

  返回系统上每个网络接口的地址信息。

语法

psutil.net_if_addrs()

返回值
返回一个字典,其中键是网络接口名称,值是一个列表,列表中的每个元素是一个命名元组,表示该网络接口的地址信息:

  • family:地址族,例如psutil.AF_INET表示IPv4psutil.AF_INET6表示IPv6
  • address:接口的IP地址
  • netmask:接口的网络掩码
  • broadcast:接口的广播地址(仅当有广播地址时)
  • ptp:点对点地址(仅当接口是点对点连接时)

示例

import psutil

# 获取系统上每个网络接口的地址信息
interfaces = psutil.net_if_addrs()

# 遍历每个网络接口的地址信息
for interface, addrs in interfaces.items():
    print(f"Interface: {interface}")
    for addr in addrs:
        print(f"  Address:       {addr.address}")
        print(f"  Netmask:       {addr.netmask}")
        if addr.broadcast:
            print(f"  Broadcast:     {addr.broadcast}")
        if addr.ptp:
            print(f"  Point-to-point:{addr.ptp}")
        print(f"  Family:        {addr.family}")
    print("-" * 40)

结果

Interface: 本地连接
  Address:       00-FF-BD-ED-28-8D
  Netmask:       None
  Family:        -1
  Address:       169.254.200.110
  Netmask:       255.255.0.0
  Family:        2
  Address:       fe80::6c3a:a939:ee82:abc
  Netmask:       None
  Family:        23
----------------------------------------
Interface: 本地连接* 1
  Address:       FC-B3-BC-E2-E1-FF
  Netmask:       None
  Family:        -1
  Address:       169.254.218.249
  Netmask:       255.255.0.0
  Family:        2
  Address:       fe80::eedc:6478:eec9:7eac
  Netmask:       None
  Family:        23
----------------------------------------
Interface: 本地连接* 2
  Address:       FE-B3-BC-E2-E1-FE
  Netmask:       None
  Family:        -1
  Address:       169.254.87.159
  Netmask:       255.255.0.0
  Family:        2
  Address:       fe80::116c:48b5:bff2:9e09
  Netmask:       None
  Family:        23
----------------------------------------
Interface: VMware Network Adapter VMnet1
  Address:       00-50-56-C0-00-01
  Netmask:       None
  Family:        -1
  Address:       192.168.6.1
  Netmask:       255.255.255.0
  Family:        2
  Address:       fe80::74aa:173a:1021:d31c
  Netmask:       None
  Family:        23
----------------------------------------
Interface: VMware Network Adapter VMnet8
  Address:       00-50-56-C0-00-08
  Netmask:       None
  Family:        -1
  Address:       192.168.111.1
  Netmask:       255.255.255.0
  Family:        2
  Address:       fe80::9b97:cdc0:158e:c53d
  Netmask:       None
  Family:        23
----------------------------------------
Interface: WLAN
  Address:       FC-B3-BC-E2-E1-FE
  Netmask:       None
  Family:        -1
  Address:       7.250.70.22
  Netmask:       255.255.255.0
  Family:        2
  Address:       fe80::7acc:6054:4b17:45fb
  Netmask:       None
  Family:        23
----------------------------------------
Interface: 以太网 2
  Address:       B0-25-AA-41-8C-E2
  Netmask:       None
  Family:        -1
  Address:       169.254.20.232
  Netmask:       255.255.0.0
  Family:        2
  Address:       fe80::cd9d:e71d:c6d6:fa2a
  Netmask:       None
  Family:        23
----------------------------------------
Interface: Loopback Pseudo-Interface 1
  Address:       127.0.0.1
  Netmask:       255.0.0.0
  Family:        2
  Address:       ::1
  Netmask:       None
  Family:        23
----------------------------------------

11.psutil.net_if_stats()

作用

  返回系统上每个网络接口的状态信息。

示例

psutil.net_if_stats()

返回值

返回一个字典,其中键是网络接口的名称,值是一个命名元组,表示该网络接口的状态信息:

  • isup:布尔值,指示接口是否启动
  • duplex:接口的duplex通信类型,可以是Nduplex(半双工),Full(全双工)或Unknown(未知)
  • speed:接口的速率(以兆比特每秒为单位),如果速率未知则为0
  • mtu:接口的MTU(最大传输单元)

示例

import psutil

# 获取系统上每个网络接口的状态信息
netstats = psutil.net_if_stats()

# 遍历每个网络接口的状态信息
for interface, stats in netstats.items():
    print(f"Interface: {interface}")
    print(f"  isup:        {stats.isup}")
    print(f"  duplex:      {stats.duplex}")
    print(f"  speed:       {stats.speed} Mbit/s")
    print(f"  mtu:         {stats.mtu}")
    print("-" * 40)

结果

Interface: 以太网 2
  isup:        False
  duplex:      2
  speed:       0 Mbit/s
  mtu:         1500
----------------------------------------
Interface: VMware Network Adapter VMnet1
  isup:        True
  duplex:      2
  speed:       100 Mbit/s
  mtu:         1500
----------------------------------------
Interface: VMware Network Adapter VMnet8
  isup:        True
  duplex:      2
  speed:       100 Mbit/s
  mtu:         1500
----------------------------------------
Interface: Loopback Pseudo-Interface 1
  isup:        True
  duplex:      2
  speed:       1073 Mbit/s
  mtu:         1500
----------------------------------------
Interface: 本地连接
  isup:        False
  duplex:      2
  speed:       1000 Mbit/s
  mtu:         1500
----------------------------------------
Interface: WLAN
  isup:        True
  duplex:      2
  speed:       173 Mbit/s
  mtu:         1500
----------------------------------------
Interface: 本地连接* 1
  isup:        False
  duplex:      2
  speed:       0 Mbit/s
  mtu:         1500
----------------------------------------
Interface: 本地连接* 2
  isup:        False
  duplex:      2
  speed:       0 Mbit/s
  mtu:         1500
----------------------------------------

12.psutil.net_connections()

作用

  获取系统上当前的网络连接信息。

语法

psutil.net_connections(kind='inet')

参数

  • kind:指定要返回的连接类型。默认值是inet,表示IPv4IPv6连接。其他可能的值有inet4(仅IPv4)、inet6(仅IPv6)和all(包括UNIX套接字)

返回值

返回一个列表,其中每个元素都是一个命名元组,代表一个网络连接:

  • fd:文件描述符
  • family:地址族,可以是psutil.AF_INETpsutil.AF_INET6psutil.AF_UNIX
  • type:套接字类型
  • laddr:本地地址(一个元组包含IP地址和端口号)
  • raddr:远程地址(一个元组包含IP地址和端口号),如果是监听套接字则为()
  • status:连接状态
  • pid:创建该连接的进程ID(如果可用)

示例

import psutil

# 获取系统上当前的IPv4和IPv6网络连接信息
connections = psutil.net_connections(kind='inet')

# 遍历每个网络连接并打印详细信息
for conn in connections:
    print(f"PID:          {conn.pid}")
    print(f"Family:       {conn.family}")
    print(f"Type:         {conn.type}")
    print(f"Local address: {conn.laddr}")
    print(f"Remote address:{conn.raddr}")
    print(f"Status:       {conn.status}")
    print("-" * 40)

结果

PID:          0
Family:       2
Type:         1
Local address: addr(ip='127.0.0.1', port=10809)
Remote address:addr(ip='127.0.0.1', port=8915)
Status:       TIME_WAIT
----------------------------------------
PID:          0
Family:       2
Type:         1
Local address: addr(ip='7.250.70.22', port=8881)
Remote address:addr(ip='45.78.49.205', port=15572)
Status:       TIME_WAIT
----------------------------------------
PID:          22720
Family:       2
Type:         1
Local address: addr(ip='127.0.0.1', port=10543)
Remote address:addr(ip='127.0.0.1', port=11051)
Status:       ESTABLISHED
----------------------------------------
PID:          28444
Family:       2
Type:         1
Local address: addr(ip='7.250.70.22', port=6536)
Remote address:addr(ip='123.182.50.164', port=443)
Status:       ESTABLISHED
----------------------------------------
...

13.psutil.pids()

作用

  获取当前系统上运行的所有进程的PID列表,返回一个列表,其中包含系统上所有正在运行的进程的PID

语法

psutil.pids()

示例

import psutil

# 获取当前系统上所有进程的PID列表
pids = psutil.pids()

# 打印PID列表
for pid in pids:
    print(pid)

结果

0
4
228
584
752
808
1096
...

14.psutil.Process()

作用

  创建一个代表系统进程的对象,这个对象可以用来获取进程的详细信息以及对其进行操作。

语法

psutil.Process(pid)

参数

  • pid:进程的PID(进程ID)

示例

import psutil

# 创建一个表示当前Python进程的Process对象
current_process = psutil.Process()

# 打印当前进程的PID
print(f"Current process PID: {current_process.pid}")

# 打印当前进程的名称
print(f"Process name: {current_process.name()}")

# 打印当前进程的执行路径
print(f"Process executable: {current_process.exe()}")

# 打印当前进程的创建时间
print(f"Process create time: {current_process.create_time()}")

# 获取当前进程的父进程PID
print(f"Parent PID: {current_process.ppid()}")

# 获取当前进程的子进程列表
print("Children PIDs:")
for child in current_process.children():
    print(f" - {child.pid}")

# 获取当前进程的内存使用信息
memory_info = current_process.memory_info()
print(f"Memory usage: {memory_info.rss / 1024 ** 2:.2f} MB")

# 获取当前进程的网络连接信息
connections = current_process.net_connections(kind='inet')
print("Network connections:")
for conn in connections:
    print(f" - Local address: {conn.laddr}, Remote address: {conn.raddr}")

# 获取当前进程的线程数量
print(f"Number of threads: {current_process.num_threads()}")

# 获取当前进程的CPU使用率
cpu_percent = current_process.cpu_percent(interval=1)
print(f"CPU usage: {cpu_percent}%")

结果

Current process PID: 29912
Process name: python.exe
Process executable: D:\Software\Python\python.exe
Process create time: 1727680063.9998543
Parent PID: 2996
Children PIDs:
 - 27908
Memory usage: 14.31 MB
Network connections:
Number of threads: 4
CPU usage: 0.0%

15.psutil.test()

作用

  内置测试功能,它会执行一系列的内部测试来验证psutil的各种功能是否正常工作。这个函数主要用于开发psutil库本身时进行测试,但用户也可以运行它来检查psutil在他们的系统上是否按预期工作,可以模拟出ps命令的效果。

语法

psutil.test()

示例

import psutil

# 执行psutil的内部测试
psutil.test()

结果

USER         PID  %MEM     VSZ     RSS  NICE STATUS  START   TIME  CMDLINE
SYSTEM         0   0.0   60.0K    8.0K        runni         14:44  System Idle P
SYSTEM         4   0.0   48.0K  152.0K        runni         35:19  System
             228   0.3   10.8M   52.1M        runni  08:51  00:02  Registry
             584   0.0    1.7M   20.0K        runni  08:51  00:00  IntelCpHeciSv
             752   0.0    1.1M    1.1M        runni  08:51  00:00  smss.exe
             808   0.0    2.8M    6.4M        runni  08:51  00:04  csrss.exe
            1096   0.0    1.5M    6.9M        runni  08:51  00:00  wininit.exe
            1104   0.0    2.9M    7.0M        runni  08:51  00:11  csrss.exe
            1108   0.0    1.9M    7.9M        runni  08:51  00:01  svchost.exe
kegehe      1112   0.6  140.6M  103.2M    32  runni  08:53  01:21  D:\Software\有
            1168   0.1    6.5M   14.8M        runni  08:51  00:18  services.exe
            1196   0.2    8.5M   24.4M        runni  08:51  00:11  lsass.exe
......
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值