Skip to main content

How to Monitor System Resources with Python

Monitoring system resources is critical for maintaining application performance and ensuring that your systems run smoothly. Python, with its simplicity and extensive library support, is an excellent tool for this task. This guide will take you through the steps of monitoring system resources using Python, providing you with practical examples and explanations to help you get started.

Why Monitor System Resources?

Have you ever wondered why your computer slows down when you open too many tabs in your browser? This slowdown usually occurs because your system resources, such as CPU and memory, are being stretched thin. Monitoring these resources helps you understand how your applications are affecting the system's performance and can alert you to potential issues before they become serious problems.

Setting Up Your Environment

Before diving into the code, ensure you have Python installed on your system. Alongside Python, you'll need some additional packages like psutil—a Python cross-platform library used for accessing system details and process utilities.

Use the following command to install psutil:

pip install psutil

Getting Started with psutil

The psutil library provides an interface for retrieving information on all running processes and system utilization (CPU, memory, disks, network, sensors) in a portable way by using Python.

Example 1: Checking CPU Usage

Here's how you can monitor CPU usage:

import psutil

# Calculate CPU usage percentage
cpu_usage = psutil.cpu_percent(interval=1)
print(f"Current CPU usage is: {cpu_usage}%")

Explanation:

  • Import psutil: First, import the psutil module that allows you to work with system resources.
  • cpu_percent: This function measures the CPU usage percentage with an optional interval parameter.
  • Print Statement: Outputs the current CPU usage.

Example 2: Monitoring Memory Usage

Next, let's see how to check memory usage:

import psutil

# Get the memory details
memory_info = psutil.virtual_memory()
print(f"Total memory: {memory_info.total} bytes")
print(f"Available memory: {memory_info.available} bytes")
print(f"Used memory: {memory_info.used} bytes")
print(f"Memory usage: {memory_info.percent}%")

Explanation:

  • virtual_memory: Retrieves statistics about system memory usage.
  • Total, Available, Used, Percent: These fields provide details about the total, available, and used memory in bytes and as a percentage.

Tracking Disk Usage

Hard disk usage can also be tracked effortlessly:

import psutil

# Get disk usage details
disk_usage = psutil.disk_usage('/')
print(f"Total disk space: {disk_usage.total} bytes")
print(f"Used disk space: {disk_usage.used} bytes")
print(f"Free disk space: {disk_usage.free} bytes")
print(f"Disk usage: {disk_usage.percent}%")

Explanation:

  • disk_usage('/'): Checks the disk usage for the root directory of your system.

Network Statistics

Network monitoring is crucial, especially for server-side applications:

import psutil

# Get network statistics
network_stats = psutil.net_io_counters()
print(f"Bytes sent: {network_stats.bytes_sent}")
print(f"Bytes received: {network_stats.bytes_recv}")

Explanation:

  • net_io_counters: Provides metrics about bytes sent and received through the network.

Monitoring Processes

Finally, tracking system processes is also possible:

import psutil

# List all running processes
for proc in psutil.process_iter(['pid', 'name', 'username']):
    print(proc.info)

Explanation:

  • process_iter: Iterates over all running processes, providing details like process ID, name, and username.

Conclusion

Monitoring system resources using Python is a powerful way to ensure that your applications are optimized and running efficiently. With libraries like psutil, you can gain insights into CPU, memory, disk, and network usage, helping you maintain peak performance.

For more in-depth programming tips and tricks, you may find it useful to explore resources on Python Comparison Operators or unlock comprehensive guides on Master Python Programming.

By incorporating these monitoring scripts into your daily workflow, you can preemptively tackle performance hurdles, ensuring smoother operations and more satisfied users.

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

Linux Network Troubleshooting

If you've spent any time as a sysadmin — or honestly, just as someone who's had to fix their own home network at 11pm — you know that connectivity issues are one of the most common headaches out there. The good news is that a handful of core tools and a methodical approach can take you from "why isn't this working" to a root cause pretty quickly.  This guide walks through the essentials: configuring interfaces, managing routes, and diagnosing problems when things go sideways. Configuring Network Interfaces Your network interfaces are the actual bridge between your machine and the outside world, so getting them configured correctly is step one for any kind of reliable connectivity. Doing It Manually ifconfig is the old-school, tried-and-true tool for this on Unix-like systems. To see everything currently configured, run: ifconfig -a If you need to manually set up a specific interface — assigning an IP, a netmask, and bringing it online — it looks like this: ifconf...