杰瑞科技汇

Linux下用Python的psutil能监控什么?

Of course! Here is a comprehensive guide to using the psutil library in Python on Linux, covering installation, core functionalities, and practical examples.

Linux下用Python的psutil能监控什么?-图1
(图片来源网络,侵删)

What is psutil?

psutil ( process and system utilities ) is a cross-platform library for Python used to retrieve information on running processes and system utilization (CPU, memory, disks, network, sensors). It's an incredibly powerful tool for system monitoring, profiling, and managing system resources.

Think of it as a swiss-army knife for system information in Python.


Installation

First, you need to install the library. It's available on PyPI, so you can use pip.

# It's good practice to use a virtual environment
python3 -m venv myenv
source myenv/bin/activate
# Install psutil
pip install psutil

psutil has no external dependencies on Linux, so the installation is straightforward.

Linux下用Python的psutil能监控什么?-图2
(图片来源网络,侵删)

Core Functionality & Examples

Let's break down the main features of psutil with practical Python code examples.

A. Process Management

This is one of the most common uses of psutil. You can iterate over all running processes, get details about a specific process, and even manage them (start, stop, terminate).

Listing All Processes

import psutil
# Iterate over all running processes
for proc in psutil.process_iter(['pid', 'name', 'username']):
    try:
        # proc.info is a dictionary containing the requested info
        print(proc.info)
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
        # These exceptions can occur if a process terminates or
        # you don't have permission to access it.
        pass

Getting Information About a Specific Process

Linux下用Python的psutil能监控什么?-图3
(图片来源网络,侵删)

You can get a process object by its PID (Process ID).

import psutil
# Get the process with PID 1 (usually 'init' or 'systemd' on modern Linux)
try:
    p = psutil.Process(1)
    print(f"Process Name: {p.name()}")
    print(f"Process ID: {p.pid}")
    print(f"Parent PID: {p.ppid()}")
    print(f"Status: {p.status()}")
    print(f"Username: {p.username()}")
    print(f"CPU Times: {p.cpu_times()}") # user, system
    print(f"Memory Info: {p.memory_info()}") # rss, vms
    print(f"Command Line: {' '.join(p.cmdline())}")
except psutil.NoSuchProcess:
    print("Process with PID 1 does not exist.")

Managing Processes (Terminating)

You can terminate a process using its PID.

import psutil
import time
# Find a process to terminate (e.g., a simple 'sleep' command)
# Open another terminal and run: sleep 1000
# Then find its PID using: ps aux | grep sleep
try:
    # Replace 'sleep' with the actual process name you want to kill
    for proc in psutil.process_iter(['pid', 'name']):
        if proc.info['name'] == 'sleep':
            pid = proc.info['pid']
            print(f"Found process 'sleep' with PID: {pid}. Terminating...")
            proc.terminate()  # Sends SIGTERM
            proc.wait(timeout=3) # Wait for the process to terminate
            print(f"Process {pid} has been terminated.")
            break
    else:
        print("No 'sleep' process found.")
except (psutil.NoSuchProcess, psutil.AccessDenied) as e:
    print(f"Error: {e}")

B. System Monitoring

psutil provides easy access to overall system performance metrics.

CPU Information

import psutil
# CPU times since boot
print("CPU Times:", psutil.cpu_times())
# CPU percentage usage (non-blocking)
print("CPU Usage (1 second interval):", psutil.cpu_percent(interval=1))
# Number of logical and physical CPU cores
print("Logical CPUs:", psutil.cpu_count(logical=True))
print("Physical CPUs:", psutil.cpu_count(logical=False))
# CPU frequency
print("CPU Frequency:", psutil.cpu_freq())

Memory Information

import psutil
# Get virtual memory statistics
mem = psutil.virtual_memory()
print("--- Virtual Memory ---")
print(f"Total: {mem.total / (1024**3):.2f} GB")
print(f"Available: {mem.available / (1024**3):.2f} GB") # Memory for apps to use
print(f"Used: {mem.used / (1024**3):.2f} GB")
print(f"Percentage: {mem.percent}%")
# Get swap memory statistics
swap = psutil.swap_memory()
print("\n--- Swap Memory ---")
print(f"Total: {swap.total / (1024**3):.2f} GB")
print(f"Used: {swap.used / (1024**3):.2f} GB")
print(f"Percentage: {swap.percent}%")

Disk Information

import psutil
# Get disk partitions
print("--- Disk Partitions ---")
for part in psutil.disk_partitions():
    print(f"Device: {part.device}, Mountpoint: {part.mountpoint}, FSTYPE: {part.fstype}")
# Get disk usage for a specific path (e.g., root '/')
print("\n--- Disk Usage for / ---")
disk_usage = psutil.disk_usage('/')
print(f"Total: {disk_usage.total / (1024**3):.2f} GB")
print(f"Used: {disk_usage.used / (1024**3):.2f} GB")
print(f"Free: {disk_usage.free / (1024**3):.2f} GB")
print(f"Percentage: {disk_usage.percent}%")
# Get disk I/O statistics
print("\n--- Disk I/O Statistics ---")
disk_io = psutil.disk_io_counters()
print(disk_io)

Network Information

import psutil
# Get network I/O statistics
print("--- Network I/O Statistics ---")
net_io = psutil.net_io_counters()
print(net_io)
# Get per-interface network I/O
print("\n--- Per-Interface Network I/O ---")
for interface, stats in psutil.net_io_counters(pernic=True).items():
    print(f"Interface: {interface}")
    print(f"  Bytes Sent: {stats.bytes_sent}")
    print(f"  Bytes Recv: {stats.bytes_recv}")
# Get network connections
# This requires root/admin privileges to see all connections
try:
    print("\n--- Network Connections ---")
    for conn in psutil.net_connections():
        if conn.status == 'ESTABLISHED':
            print(f"PID: {conn.pid}, Local: {conn.laddr}, Remote: {conn.raddr}, Status: {conn.status}")
except psutil.AccessDenied:
    print("\nAccess denied. Run as root to see all network connections.")

Putting It All Together: A Simple System Monitor

Here’s a script that continuously prints the CPU and memory usage.

# system_monitor.py
import psutil
import time
def monitor_system(interval=5):
    """Monitors and prints system CPU and memory usage at a given interval."""
    try:
        while True:
            # Get CPU usage
            cpu_percent = psutil.cpu_percent(interval=interval)
            # Get memory usage
            mem = psutil.virtual_memory()
            # Clear the console for a clean display (works on Linux/macOS)
            print("\033[H\033[J", end="")
            print("="*40)
            print(f"System Monitor (Interval: {interval}s)")
            print("="*40)
            print(f"CPU Usage: {cpu_percent:.1f}%")
            print(f"Memory Usage: {mem.percent:.1f}%")
            print(f"  - Total: {mem.total / (1024**3):.2f} GB")
            print(f"  - Available: {mem.available / (1024**3):.2f} GB")
            print(f"  - Used: {mem.used / (1024**3):.2f} GB")
            print("="*40)
            print("Press Ctrl+C to stop.")
    except KeyboardInterrupt:
        print("\nMonitoring stopped.")
if __name__ == "__main__":
    monitor_system(interval=2)

How to run it:

python3 system_monitor.py

You will see a continuously updating display of your system's resource usage.


Important Considerations on Linux

  • Permissions: Many psutil functions, especially those related to processes and network connections, require root privileges to access all information. For example, psutil.net_connections() will raise an AccessDenied error if not run as sudo.
  • Zombie Processes: On Linux, a process that has terminated but whose parent has not read its exit status becomes a "zombie" (psutil.ZombieProcess). psutil handles these gracefully, but you should be aware of them when iterating over processes.
  • /proc Filesystem: psutil on Linux primarily reads information from the /proc virtual filesystem. This is a fast and efficient way to get process and system data without needing kernel modules or special system calls.
分享:
扫描分享到社交APP
上一篇
下一篇