import psutil

This code imports the Python psutil module.

psutil (Python system and process utilities) is a cross-platform Python library for retrieving information about process and system utilization (CPU, memory, disk, network, etc.). psutil supports multiple platforms such as Windows, Linux, macOS, and FreeBSD, and provides rich APIs to easily obtain information related to operating systems and processes.

For example, the following code will output system CPU and memory usage:

import psutil

# 获取 CPU 使用率
cpu_percent = psutil.cpu_percent()
print(f"CPU 使用率: {
      
      cpu_percent}%")

# 获取内存使用率
mem = psutil.virtual_memory()
mem_percent = mem.percent
print(f"内存使用率: {
      
      mem_percent}%")

The following are several commonly used APIs:

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

    To return the system CPU usage, you can specify the sampling interval interval(in seconds), if None is specified, there will be no interval, and the CPU usage at the current moment will be returned; percputhe parameter indicates whether to return the usage of each CPU.

  • psutil.virtual_memory()

    Returns system memory usage. The return value is a named tuple (total, available, percent, used, free, active, inactive, buffers, cached, shared, slab), representing the total memory size, available memory size, memory usage, used memory size, Unused memory size, active memory size, inactive memory size, cache size, number of processes in cache, shared memory size, slab metadata size.

  • psutil.disk_usage(path)

    Returns the disk usage of the specified path. The return value is a named tuple (total, used, free, percent). Among them, total represents the total disk size, used represents the used disk size, free represents the unused disk size, and percent represents the disk usage rate.

  • psutil.net_io_counters(pernic=False)

    Return network IO statistics. The return value is a named tuple (bytes_sent, bytes_recv, packets_sent, packets_recv, errin, errout, dropin, dropout). Among them, bytes_sent represents the number of sent bytes, bytes_recv represents the number of received bytes, packets_sent represents the number of sent data packets, packets_recv represents the number of received data packets, errin represents the number of received data packet errors, errout represents the number of sent data packet errors, and dropin represents the received data The number of packets lost, dropout represents the number of lost packets sent.

Just like the sample code above, we can easily use psutil to get system and process information.

Guess you like

Origin blog.csdn.net/qq_42629529/article/details/131122063