Categories We Write About

Creating a system monitor with Python

A system monitor is a useful tool for tracking system performance metrics such as CPU usage, memory consumption, disk usage, and network activity. Python, with its wide range of libraries, offers excellent capabilities for building such monitors. This article explores how to create a comprehensive system monitoring application using Python.


Selecting Libraries for System Monitoring

To build a system monitor in Python, several libraries are essential:

  • psutil: Provides access to system details and processes.

  • tkinter or PyQt5: For GUI-based applications.

  • matplotlib or plotly: For graphical representation.

  • time and datetime: For tracking and displaying time-based metrics.

  • platform and os: For gathering system information.

Install necessary packages using pip:

bash
pip install psutil matplotlib

For GUI support:

bash
pip install PyQt5

Building the Core Monitoring Functionality

Using psutil, you can monitor the following:

CPU Monitoring

python
import psutil cpu_usage = psutil.cpu_percent(interval=1) cpu_cores = psutil.cpu_count(logical=True)

cpu_percent() returns CPU usage percentage over the specified interval. cpu_count() returns the number of logical cores.

Memory Usage

python
memory = psutil.virtual_memory() total_memory = memory.total used_memory = memory.used memory_usage_percent = memory.percent

This provides a full snapshot of current memory usage.

Disk Usage

python
disk = psutil.disk_usage('/') disk_total = disk.total disk_used = disk.used disk_percent = disk.percent

You can modify '/' to monitor other partitions.

Network Stats

python
net_io = psutil.net_io_counters() bytes_sent = net_io.bytes_sent bytes_recv = net_io.bytes_recv

These counters help in monitoring bandwidth usage.


Real-Time Monitoring Loop

A simple command-line interface to print real-time metrics:

python
import time while True: print("CPU Usage:", psutil.cpu_percent(), "%") print("Memory Usage:", psutil.virtual_memory().percent, "%") print("Disk Usage:", psutil.disk_usage('/').percent, "%") print("Network Sent:", psutil.net_io_counters().bytes_sent) print("Network Received:", psutil.net_io_counters().bytes_recv) print("-" * 40) time.sleep(2)

This loop prints fresh data every 2 seconds. You can adjust the interval as needed.


Creating a GUI with Tkinter

To make your monitor user-friendly, integrate it with a GUI.

python
import tkinter as tk from tkinter import ttk def update_metrics(): cpu = psutil.cpu_percent() memory = psutil.virtual_memory().percent disk = psutil.disk_usage('/').percent cpu_label.config(text=f"CPU Usage: {cpu}%") memory_label.config(text=f"Memory Usage: {memory}%") disk_label.config(text=f"Disk Usage: {disk}%") window.after(2000, update_metrics) window = tk.Tk() window.title("System Monitor") cpu_label = ttk.Label(window, text="") memory_label = ttk.Label(window, text="") disk_label = ttk.Label(window, text="") cpu_label.pack(pady=5) memory_label.pack(pady=5) disk_label.pack(pady=5) update_metrics() window.mainloop()

This basic GUI updates every two seconds, showing live system metrics.


Adding Graphs with Matplotlib

Integrating graphical plots enhances monitoring:

python
import matplotlib.pyplot as plt cpu_percentages = [] for _ in range(10): cpu_percentages.append(psutil.cpu_percent(interval=1)) plt.plot(cpu_percentages) plt.title("CPU Usage Over Time") plt.xlabel("Time (s)") plt.ylabel("CPU %") plt.show()

To maintain a dynamic graph, embed matplotlib into a GUI framework and use timers to refresh plots periodically.


Monitoring System Uptime and Boot Time

python
import datetime boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()) print("System Boot Time:", boot_time.strftime("%Y-%m-%d %H:%M:%S"))

This helps in determining how long the system has been running.


Enhancing with Process Monitoring

You can also monitor system processes:

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

Sorting and filtering high CPU usage processes allows detection of bottlenecks.


Logging Metrics to a File

Recording historical metrics helps with trend analysis.

python
with open("system_log.txt", "a") as log: log.write(f"{datetime.datetime.now()}, CPU: {psutil.cpu_percent()}%, Memory: {psutil.virtual_memory().percent}%n")

Set this logging to run in scheduled intervals using a background thread or a scheduler.


Developing a Web-Based Monitor

For advanced usage, you can create a web interface using Flask:

python
from flask import Flask, jsonify app = Flask(__name__) @app.route("/metrics") def get_metrics(): data = { "cpu": psutil.cpu_percent(), "memory": psutil.virtual_memory().percent, "disk": psutil.disk_usage('/').percent } return jsonify(data) if __name__ == "__main__": app.run(debug=True)

This can be visualized in a web dashboard using HTML/JavaScript frontend or integrated with frameworks like Dash or Streamlit.


Optimizing Performance and Accuracy

While building your system monitor, consider the following:

  • Avoid blocking calls: Use asynchronous programming for better responsiveness.

  • Limit resource usage: Use efficient data sampling and avoid over-polling.

  • Threading: Use threads to avoid freezing GUI during data collection.

  • Security: If building a web-based tool, secure endpoints and use authentication.


Conclusion

Creating a system monitor with Python is both practical and educational. Python’s extensive ecosystem enables real-time tracking, GUI development, data visualization, and even web deployment. Whether for personal insight or organizational needs, a Python-based system monitor provides a customizable and extensible solution for tracking system health.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

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

Categories We Write About