[Python module] psutil

1. Introduction to psutil

psutil (Python System and Process Utilities) is a cross-platform library for retrieving information about running processes and system utilization (CPU, memory, disk, network, sensors) in Python. It is mainly used for system monitoring, analysis, limiting process resources and managing running processes. It implements many functions provided by UNIX command line tools, such as: ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap. psutil currently supports Linux, Windows, macOS, FreeBSD/penBSD/NetBSD, Sun Solaris, AIX and other platforms.

The Python versions supported by psutil are 2.7 and 3.4+. Download methods on Linux, Windows, and macOS:

pip install psutil

Next, sort out the functions and APIs related to CPU, memory, disk, network, etc.

2. System related functions

2.1 CPU

CPU-related functions:

function name

function

other instructions

cpu_times(percpu=False)

Return system CPU time as a named tuple

When percpu is True, returns a list of named tuples for each logical CPU on the system. The first element of the list points to the first CPU, the second element points to the second CPU, and so on.

cpu_percent(interval=None, percpu=False)

返回表示当前系统范围内CPU利用率百分比的浮点值。

当间隔>0.0时,比较间隔前后经过的系统CPU时间(阻塞)。当interval为0.0或None时,比较自上次调用或模块导入以来经过的系统CPU时间,并立即返回。

cpu_times_percent(interval=None, percpu=False)

与cpu_percent()相同,但提供psutil.cpu_times(percpu=True)返回的每个特定cpu时间的利用率百分比。

interval和percpu参数的含义与cpu_percent()中的含义相同。

cpu_count(logical=True)

返回系统中逻辑cpu的数量(与Python 3.4中的os.cpu_count相同),如果不确定,则返回None。

“逻辑CPU”是指物理内核数乘以每个内核上可以运行的线程数(这称为“超线程”)。如果逻辑值为False,则仅返回物理内核的数量,如果未确定,则返回None。

cpu_stats()

以命名元组的形式返回各种CPU统计信息

ctx_switches:自启动以来上下文开关的数量。

interrupts:自启动以来中断数。

soft_interrupts:自启动以来软件中断数。

syscalls:自启动以来系统调用数。在Linux上始终设置为0。

cpu_freq(percpu=False)

以命名元组形式返回CPU频率,包括以Mhz表示的当前、最小和最大频率

如果percpu为True,并且系统支持每cpu频率检索(仅限Linux),则为每个cpu返回一个频率列表,如果不是,则返回一个包含单个元素的列表。如果无法确定最小值和最大值,则将其设置为0.0。

getloadavg()

以元组形式返回过去1、5和15分钟内的平均系统负载。

“负载”表示处于可运行状态的进程,使用CPU或等待使用CPU(例如等待磁盘I/O)。在UNIX系统上,这依赖于os.getloadavg。在Windows上,这是通过使用Windows API来模拟的,该API生成一个线程,该线程保持在后台运行,每5秒更新一次结果,模拟UNIX行为。因此,在Windows上,第一次调用它时,在接下来的5秒内,它将返回一个无意义的(0.0,0.0,0.0)元组。

Use demo : (current test platform --- Windows)

import psutil

# scputimes(user=2240.359305, system=2669.05, idle=20536.234305, interrupt=174.21805, dpc=443.953125)
print(psutil.cpu_times())
# 0.0
print(psutil.cpu_percent())
# scputimes(user=0.0, system=0.0, idle=0.0, interrupt=0.0, dpc=0.0)
print(psutil.cpu_times_percent())
# scpustats(ctx_switches=82697106, interrupts=58590008, soft_interrupts=0, syscalls=331427222)
print(psutil.cpu_stats())
# 8
print(psutil.cpu_count())
# scpufreq(current=1792.0, min=0.0, max=1992.0)
print(psutil.cpu_freq())
# (0.0, 0.0, 0.0)
print(psutil.getloadavg())

It can be seen from here that the CPU configuration information is: eight cores, the maximum CPU frequency is 1992MHZ, the current frequency is 1792MHZ, etc.

2.2 Memory

Memory can be divided into virtual memory and swap memory, with the following two functions:

①, virtual_memory() : Return statistics about system memory usage (in bytes) in the form of named tuples. The main indicators are:

  • total: total physical memory (exclusive swap).
  • available: available memory.
  • used: Used memory.
  • free: free memory.
  • active (UNIX): Memory currently in use or recently used.
  • inactive (UNIX): Memory marked as unused.
  • buffers (Linux, BSD): Buffers such as file system metadata.
  • cached (Linux, BSD): Caches various content.
  • shared (Linux, BSD): memory that can be accessed simultaneously by multiple processes.
  • slab (Linux): in the kernel data structure cache.
  • wired (BSD, macOS): memory marked to always remain in RAM. It is never moved to disk.
# 当前测试平台,Windows
# svmem(total=8434085888, available=1996607488, percent=76.3, used=6437478400, free=1996607488)
print(psutil.virtual_memory())

②, swap_memory() : Return system swap memory statistics as a named tuple (in bytes), including the following fields:

  • total: Exchange memory in total.
  • used: Used swap memory.
  • free: Available swap memory.
  • percent: Use percentage, calculated as (total-available)/total*100.
  • sin: The number of bytes the system has swapped from disk (cumulative).
  • sout: The number of bytes the system has swapped from disk (cumulative).
# 当前测试平台,Windows
# sswap(total=15144972288, used=8803577856, free=6341394432, percent=58.1, sin=0, sout=0)
print(psutil.swap_memory())

2.3 Disks

--> disk_partitions(): Return all mounted disk partition information in the form of a named tuple, including device, mount point, file system type, etc. If you are on the Linux platform, use the df command similarly.

--> disk_usage(path): Returns disk usage statistics about the partition containing the given path as a named tuple, including total space in bytes, used and free space, and percentage used.

--> disk_io_counters(): Return system-wide disk I/O statistics (including read_count, write_count, read_bytes, write_bytes, read_time, write_time and other fields) in the form of a named tuple.

# 当前测试平台,Windows

# [sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed', maxfile=255, maxpath=260), sdiskpart(device='D:\\', mountpoint='D:\\', fstype='NTFS', opts='rw,fixed', maxfile=255, maxpath=260)]
print(psutil.disk_partitions())

# sdiskusage(total=161051269304, used=48602433888, free=112459735616, percent=31.2)
print(psutil.disk_usage("/"))

# sdiskio(read_count=800572, write_count=166800, read_bytes=26395607296, write_bytes=7520133392, read_time=814, write_time=97)
print(psutil.disk_io_counters())

2.4 Network

--> net_io_counters(): Returns system-wide network I/O statistics in the form of a named tuple.

--> net_connections(): Return system-wide socket connections as a list of named tuples.

# 当前测试平台,Windows

#snetio(bytes_sent=1665035507, bytes_recv=16602087092, packets_sent=11453498, packets_recv=14149630, errin=0, errout=0, dropin=0, dropout=0)
print(psutil.net_io_counters())

#[sconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketKind.SOCK_STREAM: 1>, laddr=addr(ip='0.0.0.0', port=49685), raddr=(), status='LISTEN', pid=4404)]
print(psutil.net_connections())

--> net_if_addrs(): Return the address information associated with each network port installed on the system in the form of a dictionary.

--> net_if_stats(): returns the information of each network port installed on the system in the form of a dictionary (isup-identifies whether the network port is started and running normally, duplex-duplex communication type, speed-transmission speed, mtu-maximum transmission bytes, flags-flags of the network port).

# 当前测试平台,Windows

#{'本地连接* 3': [snicaddr(family=<AddressFamily.AF_LINK: -1>, address='82-91-33-91-F1-BD', netmask=None, broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET: 2>, address='169.254.163.103', netmask='255.255.0.0', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 23>, address='fe80::aa55:ee0f:3f9e:e5f0', netmask=None, broadcast=None, ptp=None)]}
print(psutil.net_if_addrs())

#{'本地连接* 3': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=0, mtu=1500)}
print(psutil.net_if_stats())

2.5 Processes

--> pids(): Returns a list of currently running pids (ordered).

--> process_iter(): Returns an iterator that generates a Process class instance for all running processes on the local computer. This should be preferred over the pids() method for iterating over processes, as it is immune to race conditions.

--> pid_exists(pid): Find out whether the specified pid exists in the list of currently running pids.

2.6 Other system information

--> users(): Returns the currently connected users on the system as a named tuple.

--> boot_time(): Returns the system boot time (in seconds) since epoch.

3. Summary

The above are most of the APIs of this module, some of which are quite practical, so record them here.

References:

psutil documentation — psutil 5.9.5 documentation

Guess you like

Origin blog.csdn.net/qq_29119581/article/details/128180387