The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Monitor CPU and memory with Python

To monitor CPU and memory usage with Python, you can use libraries like psutil, which is a popular cross-platform library for retrieving system utilization information.

Here’s a simple guide to get you started:

Step 1: Install psutil

First, you need to install the psutil library. You can install it via pip:

bash
pip install psutil

Step 2: Example Code to Monitor CPU and Memory Usage

python
import psutil import time def get_cpu_usage(): # Get the CPU usage in percentage cpu_usage = psutil.cpu_percent(interval=1) return cpu_usage def get_memory_usage(): # Get memory usage in percentage memory_info = psutil.virtual_memory() memory_usage = memory_info.percent return memory_usage def monitor_system(): while True: # Fetch CPU and memory usage cpu = get_cpu_usage() memory = get_memory_usage() # Print the current usage print(f"CPU Usage: {cpu}% | Memory Usage: {memory}%") # Wait for 1 second before repeating time.sleep(1) if __name__ == "__main__": monitor_system()

Code Explanation:

  • psutil.cpu_percent(interval=1): This function returns the CPU usage as a percentage over the specified interval (1 second in this case).

  • psutil.virtual_memory(): Returns memory statistics, and we extract the percent attribute to get the memory usage as a percentage.

  • The monitor_system() function continuously fetches and prints the CPU and memory usage every second.

Output Example:

bash
CPU Usage: 15.0% | Memory Usage: 65.3% CPU Usage: 18.7% | Memory Usage: 65.4% CPU Usage: 20.2% | Memory Usage: 65.5%

Step 3: Run the Script

You can run the script as a standalone program, and it will continuously monitor and display the CPU and memory usage in real-time.

This basic setup can be expanded or customized to fit more complex needs, such as logging the data, monitoring specific processes, or adding thresholds to trigger alerts.

Share this Page your favorite way: Click any app below to share.

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

We respect your email privacy

Categories We Write About