How to Write a Python Code for Effective System Monitoring
Here is an example of a Python script that checks system performance, including CPU, memory, disk, and network activity. This script uses the psutil
library, which works on different platforms to access system details and processes.
System Monitoring Script using Python
First, you'll need to install the psutil
library if you haven't already:
pip install psutil
Python Script:
import psutil
import time
def get_cpu_usage():
return psutil.cpu_percent(interval=1)
def get_memory_usage():
mem = psutil.virtual_memory()
return mem.percent
def get_disk_usage():
disk = psutil.disk_usage('/')
return disk.percent
def get_network_stats():
net_io = psutil.net_io_counters()
return net_io.bytes_sent, net_io.bytes_recv
def monitor_system(interval=5):
print("Starting system monitoring...")
print("Press Ctrl+C to stop.")
try:
while True:
cpu_usage = get_cpu_usage()
memory_usage = get_memory_usage()
disk_usage = get_disk_usage()
bytes_sent, bytes_recv = get_network_stats()
print(f"CPU Usage: {cpu_usage}%")
print(f"Memory Usage: {memory_usage}%")
print(f"Disk Usage: {disk_usage}%")
print(f"Network: {bytes_sent / (1024 * 1024):.2f} MB sent, {bytes_recv / (1024 * 1024):.2f} MB received")
time.sleep(interval)
except KeyboardInterrupt:
print("System monitoring stopped.")
if __name__ == "__main__":
monitor_system(interval=5) # You can change the interval as needed
Explanation:
get_cpu_usage(): Shows the CPU usage percentage. The
interval=1
parameter means it averages the CPU usage over 1 second.get_memory_usage(): Shows the percentage of used memory (RAM).
get_disk_usage(): Shows the percentage of used disk space on the root directory (
'/'
).get_network_stats(): Shows the number of bytes sent and received over the network since the system started.
monitor_system(interval=5): This function runs an endless loop that captures and shows the system stats every
interval
seconds (default is 5 seconds).try/except Block: The loop runs until the user stops it (using
Ctrl+C
). The exception handler stops the monitoring smoothly.
How to Use:
Run the script in your terminal or command prompt.
The script will start printing system statistics at the specified interval.
Press
Ctrl+C
to stop the monitoring.
Output Example:
Starting system monitoring...
Press Ctrl+C to stop.
CPU Usage: 10.3%
Memory Usage: 55.2%
Disk Usage: 40.1%
Network: 23.45 MB sent, 45.89 MB received
CPU Usage: 12.7%
Memory Usage: 55.4%
Disk Usage: 40.1%
Network: 23.47 MB sent, 45.92 MB received
Conclusion:
This script gives a simple view of your system's performance. You can add more features, like CPU temperature or process monitoring, or save the data to a file for later analysis.