SoFunction
Updated on 2025-04-08

Detailed explanation of the usage of Psutil in Python

1. Introduction

In modern server operation and maintenance, monitoring and managing system resources is crucial. Python's open source library psutil provides us with a powerful tool that can easily obtain and analyze information on system utilization (CPU, memory, disk, network, etc.). This article will lead you from getting started to advanced, to fully understand the main functions and application scenarios of psutil in server operation and maintenance, and to provide corresponding code examples and explanations.

2. The main functions and application scenarios of psutil in server operation and maintenance

1. System monitoring

psutil can obtain real-time process information of the system, including the number of processes, CPU usage, memory usage, etc., which is very useful for monitoring system performance and resource utilization.

2. Resource Management

With psutil, system resources such as CPU, memory, disk and network interfaces can be easily obtained and managed. This is very helpful for optimizing system performance, troubleshooting resource bottlenecks, and performing resource scheduling.

3. Performance testing

When performing performance testing, psutil can provide detailed system-level data to help developers analyze the performance of their applications and perform targeted optimization.

4. Troubleshooting

When there is a problem with the system, psutil can help quickly locate the problem. For example, by looking at processes with unusually high CPU usage, potential hardware or software failures can be quickly discovered.

5. Automation scripts

The psutil library can simplify the writing of automated scripts, allowing developers to perform system-level operations more conveniently. For example, you can write a script to automatically close a process that consumes a lot of resources.

6. Game server management and containerized environment monitoring

psutil can also be used for performance metric monitoring of game servers, as well as resource usage monitoring in containerized environments such as Docker and Kubernetes.

3. Psutil function code examples and explanations

1. System monitoring

Code example:

import psutil

# Get CPU usagecpu_usage = psutil.cpu_percent()
print(f"CPUUsage rate: {cpu_usage}%")

# Get memory usagememory_info = psutil.virtual_memory()
print(f"Total memory: {memory_info.total / (1024 ** 3):.2f} GB")
print(f"Memory has been used: {memory_info.used / (1024 ** 3):.2f} GB")
print(f"Memory available: {memory_info.available / (1024 ** 3):.2f} GB")
print(f"内存Usage rate: {memory_info.percent}%")

# Get disk usagedisk_info = psutil.disk_usage('/')
print(f"Total disk volume: {disk_info.total / (1024 ** 3):.2f} GB")
print(f"Disk has been used: {disk_info.used / (1024 ** 3):.2f} GB")
print(f"Disk available: {disk_info.free / (1024 ** 3):.2f} GB")
print(f"磁盘Usage rate: {disk_info.percent}%")

explain:

  • psutil.cpu_percent(): Gets the current CPU usage rate.
  • psutil.virtual_memory(): Gets memory usage and returns a named tuple containing information such as total memory, used memory, available memory and usage.
  • psutil.disk_usage('/'): Gets the usage of the disk where the root directory resides, and returns a named tuple containing information such as the total disk, used disk, available disk, and usage.

2. Resource Management

Code example:

import psutil

# Get all process informationprocesses = psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent'])
for proc in processes:
    print()

# Get specific process information (taking process with PID 1 as an example)pid = 1
proc = (pid)
print(f"processID: {}")
print(f"process名称: {()}")
print(f"CPUUsage rate: {proc.cpu_percent(interval=1)}%")
print(f"内存Usage rate: {proc.memory_percent()}%")

explain:

  • psutil.process_iter(): Iterates through all processes in the system and returns the specified information for each process.
  • (pid): Get information about a specific process through the process ID.

3. Performance testing and troubleshooting

Code example:

import psutil
import time

# Monitor CPU usage changesprint("Start monitor CPU usage...")
for i in range(10):
    cpu_usage = psutil.cpu_percent(interval=1)
    print(f"CPUUsage rate: {cpu_usage}%")
    (1)

# Find the process with the highest CPU usage ratehighest_cpu_proc = max(psutil.process_iter(['pid', 'name', 'cpu_percent']), key=lambda p: ['cpu_percent'])
print(f"CPUUsage rate最高的进程: PID={highest_cpu_proc.info['pid']}, name={highest_cpu_proc.info['name']}, Usage rate={highest_cpu_proc.info['cpu_percent']}%")

explain:

psutil.cpu_percent(interval=1): Gets the CPU usage change within a specified time interval (1 second).

max(psutil.process_iter(['pid', 'name', 'cpu_percent']), key=lambda p: ['cpu_percent']): Find the process with the highest CPU usage rate.

4. Automation script example

Code example:

import psutil

# Write a script that automatically closes processes with CPU usage exceeding 80%def close_high_cpu_processes():
    for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):
        if ['cpu_percent'] > 80:
            print(f"Close the process: PID={['pid']}, name={['name']}, Usage rate={['cpu_percent']}%")
            ()  # Terminate the process            (timeout=3)  # Wait for the process to terminate, timeout is 3 seconds            if proc.is_running():
                ()  # Force terminate process close_high_cpu_processes()

explain:

  • psutil.process_iter(['pid', 'name', 'cpu_percent']): Iterates through all processes in the system and gets the PID, name, and CPU usage of each process.
  • (): Terminate the specified process.
  • (timeout=3): Wait for the process to terminate, and if timeout, continue to perform subsequent operations.
  • (): Force terminate the specified process.

4. Advanced application

Game server management

Use psutil to monitor the performance indicators of the game server, such as frame rate, delay, etc., to ensure that the game can maintain good running results under different loads.

Containerized environment monitoring

In containerized environments such as Docker and Kubernetes, psutil is used to monitor the resource usage of containers and hosts, and help administrators allocate and schedule resources.

5. Summary

This article introduces in detail the main functions and application scenarios of psutil in server operation and maintenance, including system monitoring, resource management, performance testing, troubleshooting, automated scripting, and applications in specific fields (such as game server management and containerized environment).

This is the end of this article about the usage of Psutil in Python. For more related Python Psutil content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!