Comprehensive Guide to Python psutil Library for System Monitoring and Management

Welcome to the Ultimate Guide to Python psutil Library

The psutil library is a cross-platform tool in Python that provides an interface for retrieving vital system information and performing management tasks. With psutil, developers can monitor and control system processes, resource usage (CPU, memory, disk, network), and much more. In this guide, we’ll dive deep into psutil’s numerous APIs and provide code examples for practical use cases.

Why Use psutil

The psutil library is your go-to when building applications that require detailed insights into system performance and resource usage. It supports cross-platforms like Linux, Windows, and macOS, making it a versatile choice for any Python developer.

Installation

  pip install psutil

A Closer Look at psutil APIs

1. Retrieving CPU Information

With psutil, you can monitor CPU utilization in real time.

  import psutil

  # Get the number of CPUs
  print(psutil.cpu_count())

  # Get CPU utilization percentage
  print(psutil.cpu_percent(interval=1))

  # Get CPU stats
  print(psutil.cpu_stats())

2. Memory Information

Monitor memory usage efficiently using psutil’s API.

  # Retrieve virtual memory statistics
  mem = psutil.virtual_memory()
  print(f"Total Memory: {mem.total} bytes")
  print(f"Available Memory: {mem.available} bytes")

  # Retrieve swap memory details
  swap = psutil.swap_memory()
  print(f"Total Swap Memory: {swap.total} bytes")

3. Disk Usage and I/O Information

Discover how much disk space your system is using or monitor disk I/O activity.

  # Disk usage of '/'
  disk_usage = psutil.disk_usage('/')
  print(f"Total Disk Space: {disk_usage.total} bytes")
  print(f"Used Disk Space: {disk_usage.used} bytes")

  # Disk I/O statistics
  disk_io = psutil.disk_io_counters()
  print(f"Read Count: {disk_io.read_count}")
  print(f"Write Count: {disk_io.write_count}")

4. Network Statistics

Check network connections and monitor bandwidth usage.

  # Get network I/O statistics
  net_io = psutil.net_io_counters()
  print(f"Bytes Sent: {net_io.bytes_sent}")
  print(f"Bytes Received: {net_io.bytes_recv}")

  # Get a list of all network connections
  connections = psutil.net_connections()
  for conn in connections:
      print(conn)

5. Process Management

Control and monitor processes on your system with psutil.

  # List all current processes
  for process in psutil.process_iter(['pid', 'name', 'status']):
      print(process.info)

  # Get details of a specific process
  pid = 1234  # Replace with any valid PID
  p = psutil.Process(pid)
  print(f"Process Name: {p.name()}")
  print(f"Process Status: {p.status()}")

  # Kill a process
  p.terminate()

6. Battery Information

Monitor the battery status of a device.

  battery = psutil.sensors_battery()
  if battery:
      print(f"Battery Percentage: {battery.percent}%")
      print(f"Charging: {'Yes' if battery.power_plugged else 'No'}")
  else:
      print("No battery found!")

Real-World Application Example

Let’s build a simple monitoring application that regularly prints out system metrics.

  import psutil
  import time

  def monitor_system():
      while True:
          print("=== System Metrics ===")
          print(f"CPU Usage: {psutil.cpu_percent()}%")
          print(f"Memory Usage: {psutil.virtual_memory().percent}%")
          print(f"Disk Usage: {psutil.disk_usage('/').percent}%")
          print(f"Network Sent/Received: {psutil.net_io_counters().bytes_sent}/{psutil.net_io_counters().bytes_recv}")
          print("=====================")
          time.sleep(5)  # Update every 5 seconds

  if __name__ == "__main__":
      monitor_system()

Conclusion

psutil is an indispensable tool for Python developers looking to dive into system monitoring and management. Its extensive API allows seamless integration of system insights into your applications. Whether you’re a systems administrator, a developer, or a hobbyist, psutil simplifies your task of monitoring system performance and resource usage.

Start using psutil today and unlock a world of system-level data in your Python applications!

Leave a Reply

Your email address will not be published. Required fields are marked *