psutil in Python

Directory

1 Introduction

2. Usage

2.1 Get CPU related information

2.1.1 Get the number of physical CPU cores

2.1.2 Get the number of logical CPU cores

2.1.3 Get CPU usage

2.1.4 Get CPU time

2.1.5 Get CPU temperature

2.2 Get memory information

2.2.1 Obtain comprehensive memory information

2.2.2 Obtain the status of the swap partition

2.3 Get hard (magnetic) disk related information

2.3.1 Obtain disk partition information

2.3.2 Get specified partition information

2.3.3 Obtain disk IO status

2.4 Get network information

2.4.1 Get network interface status information

2.4.2 Network Interface Name

2.4.3 Get network connection list

2.5 Obtain process information and process control

2.5.1 Get the current process ID

2.5.2 Get the process object according to the process ID

2.5.3 Get process name

2.5.4 Get Process Status

2.5.5 CPU time occupied by processes

2.5.6 The percentage of CPU occupied by the process

2.5.7 Process memory usage

2.5.8 Process I/O Information

2.5.9 Terminating a process

3. psutil official documentation


1.Introduction

psutil is a cross-platform Python library for obtaining and managing system resource information, such as CPU, memory, disk, network, process, etc.

2. Usage

import psutil

2.1.1 Get the number of physical CPU cores

# Get the number of physical CPU cores
cores = psutil.cpu_count(logical=False) # Return an integer, indicating the number of physical CPU cores in the current system

2.1.2 Get the number of logical CPU cores

# Get the number of logical CPU cores (including hyperthreading, logical defaults to True)
logical_cores = psutil.cpu_count() # Return an integer, indicating the total number of CPU cores in the current system, including the number of physical cores and hyperthreading logical cores

2.1.3 Get CPU usage

# Get CPU usage
usage1 = psutil.cpu_percent(interval=1) # Get the CPU usage every 1 second, and return a floating point number, representing the CPU usage of the entire system.
usage2 = psutil.cpu_percent(interval=None) # Get the CPU usage only once, and return a floating-point number, representing the CPU usage of the entire system.
usage3 = psutil.cpu_percent(percpu=False) # Return a floating-point number, indicating the CPU usage of the entire system, without distinguishing the usage of each CPU core.
usage4 = psutil.cpu_percent(interval=1, percpu=False) # Get the CPU usage every 1 second, and return a floating point number, which represents the CPU usage of the entire system, without distinguishing the usage of each CPU core.
usage5 = psutil.cpu_percent(interval=1, percpu=True) # Get the CPU usage every 1 second, and return a list, each element is a floating point number, representing the usage of each CPU core.

# Obtain the occupancy rate of each CPU core (requires multiple acquisitions)
for i, percent in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
    print("{}th CPU core usage: {}%".format(i, percent))

2.1.4 Get CPU time

# get CPU time
# Which fields are included depends on the actual operating system and psutil version used.
cpu_time = psutil.cpu_times() # Return a named tuple (namedtuple), which contains the CPU time information of the current system.
# Normally, it will include metrics such as user space time, kernel space time, idle time, waiting for I/O time, hardware interrupt time, and software interrupt time, in seconds.
'''
    user: The time the CPU spent in user mode.
    system: Time spent by the CPU in system mode.
    idle: The amount of time the CPU is idle.
    interrupt: The time the CPU spent on hardware interrupts.
    dpc: Time spent by the CPU on deferred procedure calls (DPCs) (Windows only).
'''
# You can get the value of each indicator through properties like cpu_time.user, cpu_time.system, cpu_time.idle, etc. 

2.1.5 Get CPU temperature

# get CPU temperature
# The sensors_temperatures attribute cannot be used under windows system, only supports Linux and FreeBSD operating systems
temperatures = psutil.sensors_temperatures()['coretemp'][0].current

2.2 Get memory information

2.2.1 Get comprehensive memory information

# Get memory information
psutil. virtual_memory()
'''
    Usage: psutil.virtual_memory().Attributes The attributes are as follows:
    total # Get the total amount of memory
    available # get available memory
    percent # Get memory usage (total - available) / total * 100
    used # Get the currently used memory
    free # Get the current free memory
'''

2.2.2 Get the status of the swap partition

# Get the status of the swap partition
psutil. swap_memory()
'''
    total # indicates the total size of the swap partition, in bytes
    used # Indicates the size of the used swap partition, in bytes
    free # Indicates the available swap partition size in bytes
    percent # Indicates the percentage of the used swap partition, ranging from 0 to 100
    sin # Indicates the total number of bytes read from disk to the swap partition since the system was started
    sout # Indicates the total number of bytes written to disk from the swap partition since the system was started
'''

2.3.1 Get disk partition information

# Get disk partition information
psutil.disk_partitions()
'''
example:
[sdiskpart(device='C:', mountpoint='C:', fstype='NTFS', opts='rw,fixed', maxfile=255, maxpath=260)]

    device: device path (eg "/dev/hda1"). On Windows, this is the drive letter (eg "C:").
    mountpoint: mount point path (for example "/"). On Windows, this is the drive letter (eg "C:").
    fstype: The partition file system (eg "ext3" on UNIX or "NTFS" on Windows).
    opts: A comma-separated string representing the different mount options for the drive/partition. Platform dependent.
    maxfile: The maximum length a filename can have.
    maxpath: The maximum length a pathname (directory name + base filename) can have.
'''

2.3.2 Get specified partition information

# Get the specified partition information
psutil. disk_usage('path')
'''
    UNIX typically reserves 5% of the total disk space for the root user.
    total: The total capacity of the disk (in bytes) psutil.disk_usage('path').total
    used: used disk capacity (unit: byte) psutil.disk_usage('path').used
    free: The available capacity of the disk (unit is byte) psutil.disk_usage('path').free
    percent: The percentage of the used capacity of the disk to the total capacity psutil.disk_usage('path').percent
    (See https://github.com/giampaolo/psutil/blob/3dea30d583b8c1275057edb1b3b720813b4d0f60/psutil/_psposix.py#L123).
    That's why the percentage value might look 5% larger than you expect.
    Also note that all 4 values match the "df" cmdline utility.
'''

2.3.3 Get Disk IO Status

# Get disk IO status
psutil.disk_io_counters()
'''
Example: sdiskio(read_count=573575, write_count=6907229, read_bytes=34135475712, write_bytes=132917691904, read_time=2201, write_time=1452)
Return system-wide disk I/O statistics as a named tuple:
    read_count: number of reads
    write_count : write times
    read_bytes: the number of bytes read
    write_bytes: the number of bytes written

Platform-specific fields:
    read_time: (all except NetBSD and OpenBSD) time spent reading from disk in milliseconds
    write_time: (all except NetBSD and OpenBSD) time spent writing to disk in milliseconds
'''

2.4 Get network information

2.4.1 Get network interface status information

# Get network interface status information (returns a dictionary)
psutil.net_io_counters(pernic=True)
'''
    Indicates that since system startup
    bytes_sent: The number of bytes sent Usage (similar to the following): psutil.net_io_counters().bytes_sent
    bytes_recv: the number of bytes received
    packets_sent: the number of packets sent
    packets_recv: the number of packets received
    errin: the number of errors received
    errout: the number of times an error occurred while sending
    dropin: the number of packets dropped when receiving
    dropout: number of packets dropped when sending (always 0 on macOS and BSD)
'''

2.4.2 Network interface name

# get network interface name
net_io_counters.keys()

2.4.3 Get Network Connection List

# Get a list of network connections
print(psutil.net_connections())

2.5 Get process information and process control

2.5.1 Get the current process ID

# Get the current process ID
pid = os. getpid()

2.5.2 Get process object according to process ID

# Get the process object according to the process ID
p = psutil.Process(pid)

2.5.3 Get process name

# get process name
p.name()

2.5.4 Get Process Status

# get process status
p. status()

2.5.5 Process takes up CPU time

# process takes up CPU time
p.cpu_times().user

2.5.6 The percentage of the CPU used by the process

# The percentage of CPU used by the process
p.cpu_percent(interval=1)

2.5.7 Process memory usage

# process memory usage
p.memory_info().rss # unit byte (convert to MB formula: p.memory_info().rss / 1024 / 1024)

2.5.8 Process I/O Information

# I/O information of the process
p.io_counters() 

2.5.9 Terminate Process

# terminate the process
process. terminate()

3. psutil official documentation

psutil documentation – psutil 5.9.5 documentation

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledgePython entry skill treeHomepageOverview 305791 people are studying systematically