导读

psutil(process and system utilities)进程和系统实用程序,是一个跨平台的库,用于检索Python中正在运行的进程和系统利用率(CPU,内存,磁盘,网络,传感器)的信息。

系统性能信息模块

psutil(process and system utilities)进程和系统实用程序,是一个跨平台的库,用于检索Python中正在运行的进程和系统利用率(CPU,内存,磁盘,网络,传感器)的信息。 它主要用于系统监视,概要分析和限制进程资源以及管理正在运行的进程。 它实现了经典UNIX命令行工具提供的许多功能,例如ps,top,iotop,lsof,netstat,ifconfig,free等。 psutil当前支持以下平台:

Windows

macOS

FreeBSD, OpenBSD, NetBSD

Sun Solaris

AIX

【注】本文章在 python3.6,centos7.8,windows 10 下测试通过,windows下可能部分返回参数没有

安装

pip install psutil

获取CPU信息

统计cpu开销时间

psutil.cpu_times()

返回系统CPU时间

user:在用户模式下执行普通进程所花费的时间

system: 在内核模式下执行的进程所花费的时间

idle:空闲时间

nice :在用户模式下执行完好的(优先级)进程所花费的时间; 在Linux上,这还包括guest_nice时间

iowait : 等待I / O完成所花费的时间。

irq :服务硬件中断所花费的时间

softirq : 服务软件中断所花费的时间

steal : 在虚拟环境中运行的其他操作系统所花费的时间

guest :在Linux内核控制下为来guest系统运行虚拟CPU所花费的时间

guest_nice:运行良好的guest所花费的时间

如需显示所有CPU核心信息,应显示的指出psutil.cpu_times(percpu=Ture),返回一个列表, 列表的第一个元素是指第一个CPU,第二个元素是指第二个CPU,依此类推,一般情况下只关注user,system,以及idle,这三个参数,表示CPU的用户/系统/空闲时间。

# Centos7.8

>>> import psutil

>>> psutil.cpu_times()

scputimes(user=56276.04, nice=6.9, system=46298.69, idle=7267935.28, iowait=1748.04, irq=0.0, softirq=288.37, steal=0.0, guest=0.0, guest_nice=0.0)


# windows 10

>>> psutil.cpu_times(percpu=True)

[scputimes(user=120708.328125, system=113197.0625, idle=926771.3593749999, interrupt=6374.4375, dpc=3362.828125),

scputimes(user=104530.18749999999, system=87954.64062500012, idle=968191.6406249999, interrupt=1626.5625, dpc=281.8125),

scputimes(user=127384.45312499999, system=110084.546875, idle=923207.453125, interrupt=1679.453125, dpc=336.640625),

scputimes(user=110810.578125, system=82547.015625, idle=967318.875, interrupt=1359.25, dpc=262.21875)]

统计CPU利用率

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

当interval> 0.0时,将比较该间隔前后的系统CPU时间(阻塞)。 当interval为0.0或无时,比较自上次调用或模块导入以来经过的系统CPU时间,立即返回。 这意味着第一次调用它会返回一个无意义的0.0值,应该忽略它。 在这种情况下,为确保准确性,建议在两次调用之间至少调用0.1秒。

# 每隔两秒刷新CPU使用率,累计8次

>>> for x in range(8):

...     print(psutil.cpu_percent(interval=2, percpu=True))

[30.5, 17.8, 30.2, 24.6]

[16.3, 20.2, 14.0, 14.0]

[12.1, 3.9, 4.7, 3.9]

[26.4, 16.3, 18.6, 16.3]

[13.1, 9.3, 7.8, 10.1]

[33.6, 40.3, 48.4, 34.4]

[17.6, 8.5, 14.7, 7.8]

[23.1, 7.8, 21.5, 8.5]

统计CPU核心数

# 默认统计CPU逻辑核心数

>>> psutil.cpu_count() # CPU逻辑核心数

4

>>> psutil.cpu_count(logical=False) # cpu物理核心数

2

CPU频率

# 显示当前cpu的主频率

>>> psutil.cpu_freq()

scpufreq(current=1876.0, min=0.0, max=1896.0)

负载

# 以元组的形式返回最近1、5和15分钟内的平均系统负载。 在Windows上,这是通过使用Windows API模拟的,该API产生一个线程,该线程保持在后台运行,并每5秒更新一次结果,从而模仿UNIX行为。 因此,在Windows上,第一次调用此方法,在接下来的5秒钟内,它将返回无意义的(0.0,0.0,0.0)元组。

>>> psutil.getloadavg()

(0.0, 0.01, 0.05)

获取内存信息

# windows 10 返回内存使用情况

>>> memory = psutil.virtual_memory()

>>> memory

svmem(total=8463876096, available=2596061184, percent=69.3, used=5867814912, free=2596061184)

>>> memory.total

8463876096

# centos7.8

>>> psutil.virtual_memory()

svmem(total=1927192576, available=1060913152, percent=45.0, used=693989376, free=103620608, active=1383866368, inactive=288067584, buffers=143511552, cached=986071040, shared=589824, slab=93745152)


返回的是单位是字节Byte

重点关注的参数:

total=8463876096 总共8.46GB

available=2596061184 可用2.59GB

percent=69.3 使用率69.3%

used=5867814912 已使用5.86GB

获取swap 内存信息

# windows 10

>>>  psutil.swap_memory()

sswap(total=13326721024, used=9382895616, free=3943825408, percent=70.4, sin=0, sout=0)

获取磁盘信息

获取磁盘分区信息

In [35]: psutil.disk_partitions()

Out[35]: [sdiskpart(device='/dev/vda1', mountpoint='/', fstype='ext4', opts='rw,relatime,data=ordered')]

获取指定分区的使用情况

# centos 7.8

In [36]: psutil.disk_usage('/')

Out[36]: sdiskusage(total=42140479488, used=12435881984, free=27755200512, percent=30.9)

# windows 10

In [32]: psutil.disk_usage('C:\\')

Out[32]: sdiskusage(total=125917933568, used=89807781888, free=36110151680, percent=71.3)

获取硬盘的IO个数,读写信息

# windows 10

In [37]: psutil.disk_io_counters()

Out[37]: sdiskio(read_count=7703266, write_count=11199399, read_bytes=209586859008, write_bytes=217863440384, read_time=46821, write_time=5137)

# 获取单个分区的 io个数,读写信息

In [38]: psutil.disk_io_counters(perdisk=True)

Out[38]:

{'PhysicalDrive0': sdiskio(read_count=980771, write_count=399173, read_bytes=39607087616, write_bytes=8268857344, read_time=38514, write_time=1396),

'PhysicalDrive1': sdiskio(read_count=6723984, write_count=10805960, read_bytes=169995229696, write_bytes=209674449408, read_time=8309, write_time=3743)}

获取网络信息

获取网络读写字节/包的个数

# windows 10

In [39]: psutil.net_io_counters()

Out[39]: snetio(bytes_sent=45955043, bytes_recv=736052740, packets_sent=383832, packets_recv=589165, errin=0, errout=0, dropin=0, dropout=0)

# windows 10 输出每个网络接口的IO信息

In [40]: psutil.net_io_counters(pernic=True)

Out[40]:

{'Ethernet': snetio(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0),

'Local Area Connection* 11': snetio(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0),

......}

获取系统范围的套接字连接

# inet 代表 IPv4 and IPv6

In [42]: psutil.net_connections(kind='inet')

Out[42]:

[pconn(fd=115, family=, type=, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED', pid=1254),

pconn(fd=117, family=, type=, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING', pid=2987),

pconn(fd=-1, family=, type=, laddr=addr(ip='10.0.0.1', port=60759), raddr=addr(ip='72.14.234.104', port=80), status='ESTABLISHED', pid=None),

pconn(fd=-1, family=, type=, laddr=addr(ip='10.0.0.1', port=51314), raddr=addr(ip='72.14.234.83', port=443), status='SYN_SENT', pid=None)

...]

获取网络接口信息

>>> psutil.net_if_addrs()

{'lo': [snicaddr(family=, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None),

snicaddr(family=, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),

snicaddr(family=, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)],

'wlan0': [snicaddr(family=, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),

snicaddr(family=, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),

snicaddr(family=, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}

>>>

获取网络接口状态

>>> psutil.net_if_stats()

{'eth0': snicstats(isup=True, duplex=, speed=100, mtu=1500),

'lo': snicstats(isup=True, duplex=, speed=0, mtu=65536)}

获取用户信息

>>> psutil.users()

[suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0, pid=1352),

suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0, pid=1788)]

获取开机时间

In [49]: import datetime

# 获取系统开机时间,以Linux时间戳格式返回

In [50]: psutil.boot_time()

Out[50]: 1595251273.0

# 转换为人可读的方式

In [51]: datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")

Out[51]: '2020-07-20 21:21:13'

获取进程信息

获取所有进程信息

# 获取所有进程pid

In [52]: psutil.pids()

Out[52]:

[1,

2,

4,

...]

# 实例化一个Process对象,参数为进程PID

In [2]: p = psutil.Process(4313)

In [3]: p

Out[3]: psutil.Process(pid=4313, name='ipython', status='running', started='21:23:58')

# 进程bin路径

In [4]: p.exe()

Out[4]: '/usr/bin/python3.6'

# 进程工作目录绝对路径

In [5]: p.cwd()

Out[5]: '/root'

# 进程号

In [7]: p.pid

Out[7]: 4313

# 父进程号

In [8]: p.ppid()

Out[8]: 4139

# 进程状态

In [11]: p.status()

Out[11]: 'running'

# 进程 rss,vms信息

In [19]: p.memory_info()

Out[19]: pmem(rss=44388352, vms=347344896, shared=5902336, text=4096, lib=0, data=113049600, dirty=0)

# 进程内存利用率

In [20]: p.memory_percent()

Out[20]: 2.303264995557974