psutil: A Powerful Python Library!

Follow me by clicking the card above

Set a star to learn more skills

Hello everyone, today I would like to share a powerful Python library – psutil.

GitHub link: https://github.com/giampaolo/psutil

psutil (Process and System Utilities) is one of the most powerful system monitoring and process management libraries in Python. It provides a cross-platform interface for obtaining system information, allowing easy access to hardware information such as CPU, memory, disk, and network, as well as process management and system monitoring functions. Whether developing operational tools, system monitoring programs, or performance analysis applications, psutil is an indispensable tool. This library supports major operating systems like Linux, Windows, and macOS, providing developers with a unified API interface that greatly simplifies the complexity of system programming.

Installation

1. Installation Methods

# Install using pip
pip install psutil

# Or install using conda
conda install psutil

2. Verify Installation

import psutil
print(f"psutil version: {psutil.__version__}")
print(f"Number of CPU cores: {psutil.cpu_count()}")

Core Features

  • Cross-Platform Support: Supports operating systems like Linux, Windows, macOS, FreeBSD, etc.
  • Rich System Information: Obtain hardware information such as CPU, memory, disk, and network.
  • Process Management: Create, terminate, and monitor processes and their child processes.
  • Real-Time Monitoring: Provides real-time system resource usage information.
  • Network Connection Monitoring: View network connection status and statistics.
  • User Session Management: Obtain information about currently logged-in users.
  • High Performance: Implemented in C for excellent performance.

Basic Functions

1. CPU Information Retrieval

CPU usage is one of the most important metrics in system monitoring. psutil provides various ways to obtain CPU information, including overall usage, per-core usage, and CPU frequency. This information can help understand system load in real-time and provide data support for performance optimization.

import psutil
import time

# Get CPU usage
cpu_percent = psutil.cpu_percent(interval=1)
print(f"Total CPU usage: {cpu_percent}%")

# Get per-core usage
cpu_per_core = psutil.cpu_percent(interval=1, percpu=True)
for i, usage in enumerate(cpu_per_core):
    print(f"Core {i}: {usage}%")

# Get CPU frequency information
cpu_freq = psutil.cpu_freq()
print(f"CPU frequency: {cpu_freq.current:.2f}MHz")

2. Memory Information Monitoring

psutil can retrieve detailed information about physical and virtual memory, including total, used, and available amounts.

# Get memory information
memory = psutil.virtual_memory()
print(f"Total memory: {memory.total / (1024**3):.2f}GB")
print(f"Used memory: {memory.used / (1024**3):.2f}GB")
print(f"Memory usage rate: {memory.percent}%")

# Get swap partition information
swap = psutil.swap_memory()
print(f"Total swap partition: {swap.total / (1024**3):.2f}GB")
print(f"Swap partition usage rate: {swap.percent}%")

3. Disk Usage Status

psutil can retrieve the usage status of each disk partition, including total capacity, used space, and available space, helping administrators to detect disk space shortages in a timely manner.

# Get disk partition information
partitions = psutil.disk_partitions()
for partition in partitions:
    print(f"Device: {partition.device}")
    try:
        partition_usage = psutil.disk_usage(partition.mountpoint)
        print(f"  Total capacity: {partition_usage.total / (1024**3):.2f}GB")
        print(f"  Used: {partition_usage.used / (1024**3):.2f}GB")
        print(f"  Usage rate: {partition_usage.percent}%")
    except PermissionError:
        print("  Insufficient permissions")

Advanced Features

1. Process Management and Monitoring

psutil provides powerful process management capabilities, allowing retrieval of detailed information about all processes in the system, including process ID, name, CPU and memory usage, and parent-child process relationships.

# Get current process information
current_process = psutil.Process()
print(f"Current process PID: {current_process.pid}")
print(f"Process name: {current_process.name()}")
print(f"CPU usage: {current_process.cpu_percent()}%")
print(f"Memory usage: {current_process.memory_info().rss / (1024**2):.2f}MB")

# Iterate through all processes
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent']):
    if proc.info['cpu_percent'] > 10:  # Only show processes with CPU usage greater than 10%
        print(f"PID: {proc.info['pid']}, Name: {proc.info['name']}, "
              f"CPU: {proc.info['cpu_percent']}%, Memory: {proc.info['memory_percent']:.2f}%")

2. Network Connection Monitoring

The network monitoring feature helps administrators understand the network usage of the system, including network interface traffic statistics and current network connection status.

# Get network interface statistics
net_io = psutil.net_io_counters(pernic=True)
for interface, stats in net_io.items():
    print(f"Interface {interface}:")
    print(f"  Sent: {stats.bytes_sent / (1024**2):.2f}MB")
    print(f"  Received: {stats.bytes_recv / (1024**2):.2f}MB")

# Get network connection information
connections = psutil.net_connections()
for conn in connections[:5]:  # Only show the first 5 connections
    print(f"Connection: {conn.laddr} -> {conn.raddr}, Status: {conn.status}")

Real-World Application Scenarios

1. System Monitoring Script

In practical work, it is often necessary to write system monitoring scripts to monitor server status in real-time. Below is a comprehensive system monitoring example that can be used for server health checks and alert systems.

import psutil
import time
import smtplib
from datetime import datetime

def system_monitor():
    """System monitoring function"""
    # Set thresholds
    CPU_THRESHOLD = 80
    MEMORY_THRESHOLD = 85
    DISK_THRESHOLD = 90
    
    # Get system information
    cpu_usage = psutil.cpu_percent(interval=1)
    memory_usage = psutil.virtual_memory().percent
    disk_usage = psutil.disk_usage('/').percent
    
    # Check if thresholds are exceeded
    alerts = []
    if cpu_usage > CPU_THRESHOLD:
        alerts.append(f"CPU usage too high: {cpu_usage}%")
    if memory_usage > MEMORY_THRESHOLD:
        alerts.append(f"Memory usage too high: {memory_usage}%")
    if disk_usage > DISK_THRESHOLD:
        alerts.append(f"Disk usage too high: {disk_usage}%")
    
    # Log information
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_info = f"[{timestamp}] CPU: {cpu_usage}%, Memory: {memory_usage}%, Disk: {disk_usage}%"
    print(log_info)
    
    if alerts:
        print("Warning:", "; ".join(alerts))
    
    return alerts

# Continuous monitoring
while True:
    system_monitor()
    time.sleep(60)  # Check every minute

2. Process Management Tool

In multi-process applications, it is necessary to monitor and manage the status of child processes. The following example demonstrates how to use psutil to monitor the resource usage of a specific process and perform management operations when necessary.

def monitor_process_by_name(process_name):
    """Monitor process by name"""
    for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_info']):
        if process_name.lower() in proc.info['name'].lower():
            memory_mb = proc.info['memory_info'].rss / (1024**2)
            print(f"Process: {proc.info['name']}")
            print(f"PID: {proc.info['pid']}")
            print(f"CPU: {proc.info['cpu_percent']}%")
            print(f"Memory: {memory_mb:.2f}MB")
            
            # If memory usage exceeds 1GB, issue a warning
            if memory_mb > 1024:
                print("Warning: This process is using too much memory!")

# Monitor Python processes
monitor_process_by_name("python")

Conclusion

As one of the best system monitoring libraries in the Python ecosystem, psutil provides developers with comprehensive and powerful system information retrieval and process management capabilities. Through this article, we have learned about the core features of psutil, basic usage methods, and advanced functional applications. Whether for simple system information queries or complex server monitoring system development, psutil can handle it all. Its cross-platform characteristics ensure good portability of the code, and the unified API interface greatly reduces the learning curve. In practical projects, effectively utilizing psutil can help us build efficient monitoring systems, performance analysis tools, and automated operation and maintenance scripts, significantly improving the efficiency and quality of system management.

In the AI era, the maturity of AI tools has given programmers capabilities that were previously unimaginable. The vast overseas market provides us with a larger stage.

If you are also considering new paths, if you want to try AI programming in the overseas market, feel free to join us.

Recommended Reading👉️: I recommend my AI programming overseas training camp!

Scan the code or search for 257735 to add WeChat, send the code “USD” to learn more details.

psutil: A Powerful Python Library!

Leave a Comment