Python System Monitoring and Operation and Maintenance Guide: Using the psutil module
Use on Linuxtop、free, you have to open the Task Manager when switching to Windows, and you have to find the Activity Monitor on macOS... If you have ever been tortured by these fragmented system tools, then psutil is your savior. It uses a unified Python interface to put all core information such as CPU, memory, disk, network, and process into your pocket. Its cross-platform compatibility is as high as over 95%. It is a must-have artifact for operation and maintenance engineers and back-end developers.
1. Introduction: What can psutil do?
psutil(process and system utilities) is a lightweight and high-performance Python library specifically used to capture the underlying operating status of the system. It can replace those traditional scriptstop、vmstat、iostatCommand line tool calls like this can make your code cleaner and more cross-platform.
Covered scenarios include but are not limited to: -CPU usage, number of physical/logical cores, time statistics
- Detailed usage of physical memory and swap area (Swap)
- Disk partitions, mount points, disk I/O statistics
- Network interface status and global traffic statistics
- Process list, process details (PID, CPU/memory usage, startup time, etc.)
- Battery status, sensor temperature (supported by specific platforms)
Whether it is to temporarily troubleshoot problems or integrate monitoring into back-end services, it can do the job efficiently.
2. Installation
Install the stable version with one line of command:
If you have insufficient permissions when installing to global packge on Linux/macOS, addsudo:
After the installation is complete, importpsutilYou are ready to start using it.
3. Quick overview of core functions
The most practical codes are shown below in modules according to the high-frequency needs of operation, maintenance and development.
3.1 CPU Monitoring
Static information: number of cores, cumulative time
Real-time usage
similartopFor real-time sampling, you can set the sampling interval and subdivide it to each core:
Tip:
cpu_percent()The first call of will return a meaningless value of 0 because it needs to be compared with the previous one. In actual use, you would use a loop as above and setintervalto get accurate results.
3.2 Memory Monitoring
psutilYou can view physical memory and swap area (Swap) information at the same time. All values are in bytes by default, and we usually convert them to more readable GB.
availableThis field is very considerate: it indicates the memory that the system thinks is currently available for allocation to the new process, which is better than simplyfreeMore practical.
3.3 Disk monitoring
Partitions and mount points
The following code iterates through all disk partitions, printing mount points, file system types, and usage. Some special file systems (such astmpfs、snapetc.) We have done filtering to make the output clearer.
Global disk I/O
If you need to monitor a specific disk device, you can use the parameterperdisk=TrueGet I/O statistics for each disk.
3.4 Network Monitoring
Global traffic and interface status
In this way, you can quickly locate which network card is working and what the current MTU is, which is very helpful for network troubleshooting.
3.5 Process Management
Process management ispsutilOne of the most powerful parts. You can list all processes, get details about a process, and even kill a process.
First, let’s take a look at the total number of processes in the system and information about the current Python process:
In actual operation and maintenance, we often need to find the process with the highest CPU or memory usage. The following function encapsulates a method to safely obtain process information and prints the top 5 CPU killers:
Performance reminder: If you need to traverse a large number of processes, please use it first
psutil.process_iter(), which is better thanpids()+Process()way performance is over 30% higher.
4. Practical tips and precautions
4.1 Practical tips
- Efficient process traversal: use
psutil.process_iter()Get all process objects at once to avoid repeated construction. - Cross-platform compatibility check: Some functions (such as battery status, temperature sensor) only exist on specific platforms. use
hasattr(psutil, "sensors_battery")To determine whether the function is available and avoid the code reporting errors on other systems. - Timestamp conversion:
create_time()What is returned is the Unix timestamp, paired withdatetime.datetime.fromtimestamp()That is converted to human readable time. - Sampling interval for long-term monitoring:
cpu_percent(interval=…)orProcess.cpu_percent(interval=…)It is recommended that the interval be set to 1~5 seconds to avoid excessive CPU overhead caused by too short an interval.
4.2 Notes
- Permission issues
Operations such as viewing other users' processes and obtaining network connection details usually require root or administrator privileges, otherwise it will throw
AccessDeniedabnormal. - exception-handling three brothers
When processing a process, you must override
NoSuchProcess(The process has exited),AccessDenied(insufficient permissions) andZombieProcess(Linux zombie process), otherwise the program may crash unexpectedly. - Performance overhead
psutilIt is lightweight in itself, but frequent calls to underlying system interfaces still consume CPU. When designing monitoring services, pay attention to controlling the sampling frequency and caching information that does not change frequently.
5. Summary
psutilUsing a set of concise and unified APIs to solve the pain points of cross-platform system monitoring can be said to be the "ceiling" of system tools in the Python ecosystem. Whether you are writing a random script to check the server status, or weaving monitoring indicators into the web service of the production environment, it can help you get twice the result with half the effort.
What is shown above is just the tip of the iceberg. More advanced functions (such as process termination, network connection list, hardware sensor data) can be found in psutil 官方文档. take you fromtop、netstat、freeliberated from the shackles of apip install psutilLet’s get started!

