Computer Hardware

Python Script To Monitor CPU Usage In Linux

Imagine being able to effortlessly monitor the CPU usage of your Linux system with just a few lines of Python script. This powerful tool allows you to not only keep track of your system's performance but also optimize it for enhanced efficiency. By gaining insights into how your CPU is being utilized, you can identify any bottlenecks or resource-intensive processes that may be hindering your system's performance and take appropriate action.

The Python script to monitor CPU usage in Linux provides a simple yet effective solution for users seeking to keep their systems running smoothly. With its history rooted in the open-source community, Python neatly combines the features of a functional programming language with powerful libraries that make it a versatile choice for system monitoring tasks. By harnessing the script's capabilities, system administrators can detect and analyze CPU usage patterns, enabling them to make informed decisions about resource allocation and performance optimization throughout their Linux environments.



Python Script To Monitor CPU Usage In Linux

Introduction: Monitoring CPU Usage in Linux with Python

Python is a versatile programming language that is widely used for various tasks, including system administration. One of the essential aspects of system administration is monitoring the CPU usage. CPU usage monitoring helps in understanding the performance of a system and identifying potential bottlenecks or resource-intensive processes. In Linux, there are several tools available for monitoring CPU usage, but using a Python script provides the flexibility to customize the monitoring process according to specific requirements. In this article, we will explore how to write a Python script to monitor CPU usage in Linux.

Understanding CPU Usage in Linux

Before diving into writing a Python script to monitor CPU usage, it is important to understand how CPU usage is calculated in Linux. CPU usage refers to the amount of time the CPU spends on various tasks or processes. In Linux, CPU usage is represented in terms of percentages, indicating the proportion of time the CPU spends in different states:

  • User CPU Usage: This represents the time the CPU spends executing user processes, such as running applications or commands.
  • System CPU Usage: This represents the time the CPU spends executing system processes, such as kernel operations or system services.
  • Idle CPU Usage: This represents the time the CPU is idle and not executing any processes.
  • I/O Wait CPU Usage: This represents the time the CPU spends waiting for input/output operations to complete.
  • Hardware Interrupt CPU Usage: This represents the time the CPU spends handling hardware interrupts, such as signals from devices.

By monitoring these different CPU usage states, it is possible to gain insights into the overall system performance and identify any issues or bottlenecks that may be impacting the CPU utilization.

Measuring CPU Usage Using Python

To measure CPU usage in Linux using Python, we can utilize system commands such as top or psutil. The top command provides real-time information about system performance, including CPU usage. The psutil library, on the other hand, is a cross-platform library that exposes system details, including CPU usage, in a simple and convenient manner.

Here's a sample Python script that uses the psutil library to monitor CPU usage:

import psutil
import time

while True:
    cpu_percent = psutil.cpu_percent(interval=1, percpu=True)
    print(f"CPU Usage: {cpu_percent}")
    time.sleep(1)

In the above script, we import the psutil library and the time module. We then enter an infinite loop to continuously monitor the CPU usage. The cpu_percent variable stores the CPU usage as a list of percentages for each CPU core. We use the print statement to display the CPU usage, and then sleep for a second before continuing to the next iteration.

By running this script, we can continuously monitor the CPU usage in Linux and observe any fluctuations or patterns in the CPU utilization.

Customizing CPU Monitoring with Python

While the above script provides a basic monitoring capability, it can be further customized to suit specific requirements. Here are a few ways to customize CPU monitoring using Python:

  • Recording CPU Usage: Instead of displaying CPU usage in real-time, the script can be modified to record CPU usage over a specific duration and store it for further analysis.
  • Threshold Monitoring: The script can be enhanced to check for specific thresholds and trigger alerts or actions when the CPU usage exceeds predefined limits.
  • Monitoring Remote Systems: Using additional modules, such as paramiko or ansible, the script can be extended to monitor CPU usage on remote systems and gather data centrally.
  • Visualization: The matplotlib library can be used to create graphical representations of CPU usage data, making it easier to analyze and interpret trends over time.

Example: Recording and Plotting CPU Usage

Let's consider an example where we modify the Python script to record CPU usage over a specific duration and plot it using the matplotlib library. Here's an updated script:

import psutil
import time
import matplotlib.pyplot as plt

cpu_percent_data = []
time_data = []

duration = 60
start_time = time.time()

while time.time() - start_time < duration:
    cpu_percent = psutil.cpu_percent(interval=1, percpu=False)
    cpu_percent_data.append(cpu_percent)
    time_data.append(time.time() - start_time)
    time.sleep(1)

plt.plot(time_data, cpu_percent_data)
plt.xlabel('Time (s)')
plt.ylabel('CPU Usage (%)')
plt.title(f'CPU Usage Over {duration} seconds')
plt.show()

In this updated script, we import the additional matplotlib.pyplot module to plot the CPU usage data. We define two lists, cpu_percent_data and time_data, to store the CPU usage and corresponding time values. The duration variable determines the recording duration.

Within the loop, we append the CPU percentage and time values to their respective lists. Once the recording duration is complete, we use the plt.plot() function to plot the CPU usage over time. Additional plt.xlabel(), plt.ylabel(), and plt.title() functions provide labels and a title to the plot. Finally, we use plt.show() to display the plot.

By modifying the script in this way, we can visualize the CPU usage over time, enabling us to identify any spikes, trends, or patterns that may require further investigation.

Monitoring CPU Usage made Easy with Python

Python provides a versatile and flexible platform to monitor CPU usage in Linux systems. By utilizing the psutil library and additional modules, such as matplotlib or paramiko, it is possible to create customized scripts that meet specific monitoring requirements.

Whether it's recording CPU usage over a specific duration, setting threshold alerts, or monitoring remote systems, Python enables system administrators to gain deeper insights into CPU performance and ensure optimal utilization of system resources.

Using Python to monitor CPU usage simplifies the process and provides the flexibility to adapt the monitoring approach as needed. By combining Python's simplicity with the power of system commands and libraries, system administrators can effectively monitor CPU usage and make informed decisions to optimize system performance.


Python Script To Monitor CPU Usage In Linux

Monitoring CPU Usage in Linux with Python

Monitoring the CPU usage in a Linux system is crucial for system administrators and developers to optimize performance and identify any potential issues. With Python, you can easily create a script to monitor CPU usage in Linux.

To monitor CPU usage in Linux using Python, you can utilize the psutil library, which provides an easy interface to retrieve system information. This library allows you to access various system resources, including CPU usage.

Here are the steps to create a Python script to monitor CPU usage in Linux:

  • Import the psutil library.
  • Retrieve CPU usage information using the psutil.cpu_percent() method.
  • Print or log the CPU usage information as required.
  • Repeat the process at a desired interval to continuously monitor CPU usage.

By regularly monitoring CPU usage in Linux, you can detect any resource-intensive processes or bottlenecks that may be affecting system performance. This allows you to take necessary actions such as optimizing resource allocation or identifying and fixing issues.


Key Takeaways:

  • Python has libraries that allow you to monitor CPU usage in a Linux system.
  • Using the psutil library in Python, you can retrieve CPU utilization statistics.
  • You can monitor CPU usage in real-time or collect historical data for analysis.
  • With the psutil library, you can get information on CPU usage, including user, system, idle, and per-cpu percentages.
  • By monitoring CPU usage, you can optimize your system's performance and identify bottlenecks.

Frequently Asked Questions

Here are some common questions about Python scripts to monitor CPU usage in Linux.

1. How can I write a Python script to monitor CPU usage in Linux?

To write a Python script that monitors CPU usage in Linux, you can use the psutil library, which provides an interface to retrieve system information, including CPU usage. First, you need to install psutil by running the command "pip install psutil" in your terminal. Then, you can import the psutil module in your Python script and use the "psutil.cpu_percent()" function to get the current CPU usage as a percentage.

Here's an example of a Python script using psutil to monitor CPU usage:

import psutil

while True:
    cpu_percent = psutil.cpu_percent(interval=1)
    print(f"CPU Usage: {cpu_percent}%")

2. How often should I monitor CPU usage with my Python script?

The frequency at which you monitor CPU usage with your Python script depends on your specific needs. If you're looking for real-time monitoring, you can use a while loop with a short interval, such as 1 second, to continuously retrieve CPU usage information. However, if you're only interested in periodic monitoring, you can adjust the interval accordingly. Keep in mind that more frequent monitoring may consume more system resources.

3. Can I save the CPU usage data collected by my Python script?

Yes, you can save the CPU usage data collected by your Python script to a file for further analysis or record-keeping purposes. You can open a file in write mode using the "open()" function and write the CPU usage data to the file using the "write()" or "writelines()" method. Make sure to properly close the file after writing to ensure data integrity.

4. Can I send notifications based on CPU usage thresholds using my Python script?

Yes, using a Python script, you can monitor CPU usage and send notifications based on specific thresholds. You can set up conditional statements to check the CPU usage percentage and trigger a notification when it exceeds a certain threshold. For example, you can use the smtplib library to send an email notification or the notify2 library to display a desktop notification when the CPU usage reaches a critical level.

5. Are there any other Python libraries I can use to monitor CPU usage in Linux?

Yes, apart from psutil, there are other Python libraries available to monitor CPU usage in Linux. Some popular options include:

  • py-cpuinfo: A library that retrieves CPU information, including usage, load, and temperature.
  • pycpustat: A library that provides more detailed CPU statistics, including per-CPU usage and process-level information.
  • glances: A comprehensive system monitoring tool that offers CPU usage monitoring along with other system metrics.


In summary, monitoring CPU usage in Linux using a Python script is a powerful tool that allows users to effectively manage system performance. By utilizing the psutil library and the Linux operating system's built-in tools, users can easily obtain real-time and historical data on CPU usage, enabling them to identify and address performance bottlenecks.

With the Python script, users have the flexibility to customize their monitoring parameters and integrate the data into other monitoring systems or visualization tools. This script offers a convenient and efficient way to monitor CPU usage in Linux, empowering users to optimize their system's performance and ensure smooth operations.


Recent Post