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:
Step 2: Example Code to Monitor CPU and Memory Usage
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 thepercentattribute 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:
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.