SoFunction
Updated on 2025-05-16

Python uses psutil to implement system monitoring and resource management

In the fields of system operation and maintenance, resource monitoring, performance analysis, service status diagnosis, etc., developers often need to obtain the underlying information of the operating system, such as CPU usage, memory usage, disk reading and writing, network transmission, process details, etc. Although these functions can be implemented through shell commands such as top, df, ps, iostat, etc., in automated scripts and cross-platform development, it is more flexible and portable to use Python scripts to complete these tasks.

This is where psutil comes in - a powerful cross-platform system monitoring library that can easily obtain various system resource status and process information, and supports Linux, Windows, macOS and other platforms.

This article will explain in-depth the functions of psutil, and combine actual code examples to show how to use Python to build your own system monitoring tools, resource analyzers, process management scripts, etc.

1. Introduction to psutil

psutil is the abbreviation of "process and system utilities". It is a cross-platform system monitoring library for:

  • Obtain the usage of CPU, memory, disk, network and other systems
  • Manage and obtain process information
  • Implement task monitoring, resource tracking and system health checks
  • Provide functional interfaces for Unix ps, top, df, netstat, lsof and other commands

Its original design is to replace the tedious approach of encapsulating shell commands with Python, providing a consistent, elegant, and excellent performance API.

2. Installation and basic use

Installation method

Installation using pip is very simple:

pip install psutil

Once installed, it can be started almost immediately without additional configuration.

Quick example: Get current CPU usage

import psutil

print("Current CPU Usage:", psutil.cpu_percent(interval=1), "%")

cpu_percent() indicates that the overall CPU usage is measured within a specified time interval (such as 1 second).

3. CPU information monitoring

1. Get the number of CPU logical/physical cores

print("Physical core number:", psutil.cpu_count(logical=False))
print("Logistic core number:", psutil.cpu_count(logical=True))

2. Usage rate per core

import time

for _ in range(5):
    usage = psutil.cpu_percent(interval=1, percpu=True)
    print("Per-core usage:", usage)

3. Obtain CPU time information

times = psutil.cpu_times()
print(f"user: {}, system: {}, idle: {}")

This API provides a system-level CPU time distribution.

4. Memory information monitoring

1. Obtain virtual memory usage

mem = psutil.virtual_memory()
print(f"Total memory: { / 1024 ** 3:.2f} GB")
print(f"Used: { / 1024 ** 3:.2f} GB")
print(f"idle: { / 1024 ** 3:.2f} GB")
print(f"Usage rate: {}%")

2. Get swap swap partition information

swap = psutil.swap_memory()
print(f"Swap Total quantity: { / 1024 ** 3:.2f} GB")
print(f"Usage rate: {}%")

5. Disk information monitoring

1. Obtain disk partition information

partitions = psutil.disk_partitions()
for p in partitions:
    print(f"Mounting point: {}, type: {}")

2. Get disk usage

usage = psutil.disk_usage('/')
print(f"Total space: { / 1024 ** 3:.2f} GB")
print(f"Used: { / 1024 ** 3:.2f} GB")
print(f"Remaining: { / 1024 ** 3:.2f} GB")

3. Real-time disk IO situation

io = psutil.disk_io_counters()
print(f"Read bytes: {io.read_bytes / 1024 ** 2:.2f} MB")
print(f"Writing bytes: {io.write_bytes / 1024 ** 2:.2f} MB")

6. Network information monitoring

1. Obtain network IO situation

net = psutil.net_io_counters()
print(f"send: {net.bytes_sent / 1024 ** 2:.2f} MB")
print(f"take over: {net.bytes_recv / 1024 ** 2:.2f} MB")

2. Obtain network card information

addrs = psutil.net_if_addrs()
for iface, infos in ():
    print(f"\nNetwork card: {iface}")
    for info in infos:
        print(f"  address: {} ({})")

3. Current network connection

conns = psutil.net_connections(kind='inet')
for conn in conns[:5]:
    print(f"connect: {} -> {}, state: {}")

7. Process Management

1. Enumerate all current processes

for proc in psutil.process_iter(['pid', 'name', 'username']):
    print()

2. Get detailed information about the specified process

p = (1)  # PID 1 is usually init or systemdprint(f"name: {()}")
print(f"path: {()}")
print(f"state: {()}")
print(f"CPUUsage rate: {p.cpu_percent(interval=1.0)}")
print(f"Memory usage: {p.memory_info().rss / 1024 ** 2:.2f} MB")

3. Operation process (terminate, suspend, restore)

p = (1234)
()  # Hang up()   # recover()  # Termination

Note: Administrator permissions or root permissions are required to operate other users' processes.

8. Build a simple system resource dashboard

You can use psutil + rich or psutil + flask/streamlit to build beautiful graphics or terminal dashboards. Here is a simple terminal monitoring:

import psutil
import time
import os

def monitor():
    while True:
        ('cls' if  == 'nt' else 'clear')
        print("=== Real-time system resource monitoring ===")
        print(f"CPU Usage rate: {psutil.cpu_percent()}%")
        mem = psutil.virtual_memory()
        print(f"Memory: { / 1024 ** 3:.2f} GB / { / 1024 ** 3:.2f} GB ({}%)")
        net = psutil.net_io_counters()
        print(f"network: send {net.bytes_sent / 1024 ** 2:.2f} MB, take over {net.bytes_recv / 1024 ** 2:.2f} MB")
        (1)

if __name__ == "__main__":
    monitor()

It can be expanded to a web dashboard, and even connected to Grafana and Prometheus for data reporting.

9. Advanced usage and practical cases

1. Write a daemon script that automatically kills high CPU occupancy processes

def auto_kill(threshold=80):
    for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):
        try:
            if ['cpu_percent'] > threshold:
                print(f"Kill Gao CPU process: {}")
                (['pid']).terminate()
        except (, ):
            continue

2. Cross-platform performance analysis tools

You can use psutil to collect data and log:

import json
import datetime

def log_stats():
    stats = {
        "time": str(()),
        "cpu": psutil.cpu_percent(),
        "mem": psutil.virtual_memory().percent,
        "disk": psutil.disk_usage('/').percent,
    }
    with open("", "a") as f:
        ((stats) + "\n")

Can be used for long-term machine running status monitoring and visual analysis.

10. Summary and Outlook

psutil is a very mature, stable, well-documented Python library that can meet almost all your needs for operating system resource access, including but not limited to:

  • Task Manager Alternative Script
  • DevOps Operation and Maintenance Tools
  • System performance analysis
  • Automated testing platform
  • AI training task resource scheduling

Advantages:

  • Strong cross-platform support (Windows/Linux/macOS)
  • API intuitive and clear structure
  • Rich in documents and active community
  • Can be integrated into various Python toolchains

Notes:

  • Some operations (such as killing processes, accessing other user processes) may require administrator permissions.
  • Pay attention to exception handling when traversing a large number of system processes (AccessDenied, NoSuchProcess)

This is the article about Python using psutil to implement system monitoring and resource management. For more related Python psutil monitoring system and resource content, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!