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 |
|
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. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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: