How to Make a Process Monitor in Python?

Posted in /  

How to Make a Process Monitor in Python?
vinaykhatri

Vinay Khatri
Last updated on December 25, 2024

    Every operating system comes with a task manager or system monitor where you can see your running applications. Also, you can see their CPU usage, memory usage, and status. From there, you can also kill any process or application that is taking too many CPU resources.

    Although you can easily open your task manager to monitor all processes, it would be cool if you knew how to make a process monitor in Python.

    In this Python tutorial, we will walk you through a Python program that allows you to keep track of applications and processes running on your system. Before we dive into the Python code, let's install the libraries that we will be using in this tutorial.

    Install Libraries

    1. Python psutil Library

    Python psutil is a Python system and process utility library. With the help of this library, we can get information about the running processes and system utilization (CPU, memory, and so on). It is a cross-platform library.

    Therefore, it can be used with all the popular operating systems, including Windows, Linux, macOS, FreeBSD, Sun Solaris, and AIX. To install the psutil library for your Python environment, run the following pip install command on your terminal:

    pip install psutil

    2. Python pandas Library

    pandas is one of the most popular Python data science libraries . It is well known for its high-performance computation with arrays and multi-dimensional arrays like Series and DataFrame.

    In this tutorial, we will be using pandas to show all the process lists and filter them according to memory usage. To install pandas, run the following pip install command on your terminal:

    pip install pandas

    How to Make a Process Monitor in Python?

    Alright then, open any best Python ide or text editor and code along. Let's begin with importing the modules that we will be using in our Python program.

    import psutil           #pip install psutil
    import datetime
    import pandas as pd     #pip install pandas

    Now, let's define some empty Python list identifiers that will store the detail about the process.

    pids = []
    name = [] 
    cpu_usage= []
    memory_usage = []
    memory_usage_percentage =[]
    status =[]
    create_time =[]
    threads =[]

    The psutil module provides a process_iter() Python generator function that can iterate over all the processes running on the local system.

    for process in psutil.process_iter():
        pids.append(process.pid)
        name.append(process.name())
    
        cpu_usage.append(process.cpu_percent(interval=1)/psutil.cpu_count())
    
        memory_usage.append(round(process.memory_info().rss/(1024*1024),2))
    
        memory_usage_percentage.append(round(process.memory_percent(),2))
    
        create_time.append(datetime.datetime.fromtimestamp(process.create_time()).strftime("%Y%m%d - %H:%M:%S"))
    
        status.append(process.status())
    
        threads.append(process.num_threads())
    • The pid() function returns the process id number.
    • name() returns the name of the process.
    • The cpu_percent() function returns the percentage of CPU utilization of the process.
    • memory_info() returns a dictionary of different types of memory usage by the process. In the memory_info() function, the rss attribute represents Resident Set Size or the physical memory of the process.
    • The memory_percent() function returns the process memory percentage by comparing the process memory to the system memory.
    • The create_time() function returns the process creation time in seconds.
    • status() returns the running status of the process.
    • num_threads() returns the number of threads used by the process.
    • The append() function will add the return value to the list.
    • The round() function will sound up the decimal point number up to 2 digits.
    • fromtimestamp() will convert the creation time seconds in a readable time format.
    • The strftime() function will convert the date-time object to a readable string.

    Next, let's create a data dictionary that will contain all the process details.

    data = {"PIds":pids,
            "Name": name,
            "CPU":cpu_usage,
            "Memory Usages(MB)":memory_usage,
            "Memory Percentage(%)": memory_usage_percentage,
            "Status": status,
            "Created Time": create_time,
            "Threads": threads,
            }

    Now, convert the dictionary into a pandas DataFrame using the DataFrame function.

    process_df = pd.DataFrame(data)

    Next, let's set the index value to PIds , sort the process according to their memory usages, and add MB at the end of every process memory.

    #set index to pids
    process_df =process_df.set_index("PIds")
    
    #sort the process 
    process_df =process_df.sort_values(by='Memory Usages(MB)', ascending=False)
    
    #add MB at the end of memory
    process_df["Memory Usages(MB)"] = process_df["Memory Usages(MB)"].astype(str) + " MB"
    
    print(process_df)

    Finally, put all the code together and execute.

    Python Program to Make a Process Monitor

    import psutil
    import datetime
    import pandas as pd
    
    pids = []
    name = [] 
    cpu_usage= []
    memory_usage = []
    memory_usage_percentage =[]
    status =[]
    create_time =[]
    threads =[]
    
    for process in psutil.process_iter():
        pids.append(process.pid)
        name.append(process.name())
    
        cpu_usage.append(process.cpu_percent(interval=1)/psutil.cpu_count())
    
        memory_usage.append(round(process.memory_info().rss/(1024*1024),2))
    
        memory_usage_percentage.append(round(process.memory_percent(),2))
    
        create_time.append(datetime.datetime.fromtimestamp(process.create_time()).strftime("%Y%m%d - %H:%M:%S"))
    
        status.append(process.status())
    
        threads.append(process.num_threads())
    
    data = {"PIds":pids,
            "Name": name,
            "CPU":cpu_usage,
            "Memory Usages(MB)":memory_usage,
            "Memory Percentage(%)": memory_usage_percentage,
            "Status": status,
            "Created Time": create_time,
            "Threads": threads,
            }
    
    process_df = pd.DataFrame(data)
    #set index to pids
    process_df =process_df.set_index("PIds")
    
    #sort the process 
    process_df =process_df.sort_values(by='Memory Usages(MB)', ascending=False)
    
    #add MB at the end of memory
    process_df["Memory Usages(MB)"] = process_df["Memory Usages(MB)"].astype(str) + " MB"
    
    print(process_df)

    Output

                                Name     CPU Memory Usages(MB)  \  
    PIds                                                         
    4600                 MsMpEng.exe   0.000         612.82 MB   
    2652              MemCompression   0.000         484.56 MB   
    12452                 chrome.exe   0.000         311.19 MB   
    17224                 chrome.exe   0.000         283.71 MB   
    15024                 chrome.exe   0.000         197.44 MB   
    ...                          ...     ...               ...   
    19008                RAVBg64.exe   0.000           0.22 MB   
    8368    GoogleCrashHandler64.exe   0.000           0.18 MB   
    3168          SystemSettings.exe   0.000           0.15 MB   
    10608  MySQLInstallerConsole.exe   0.000           0.09 MB   
    0            System Idle Process  90.625           0.01 MB   
    
           Memory Percentage(%)   Status         Created Time  Threads  
    PIds                                                                
    4600                   7.60  running  20210215 - 16:38:45       29  
    2652                   6.01  running  20210215 - 16:38:39       46  
    12452                  3.86  running  20210218 - 10:44:47       15  
    17224                  3.52  running  20210218 - 10:44:44       30  
    15024                  2.45  running  20210218 - 10:51:06       15  
    ...                     ...      ...                  ...      ...  
    19008                  0.00  running  20210218 - 10:42:23        4  
    8368                   0.00  running  20210215 - 16:41:46        3  
    3168                   0.00  stopped  20210218 - 11:14:54       24  
    10608                  0.00  running  20210218 - 10:36:16        4  
    0                      0.00  running  19700101 - 05:30:00        4

    When you execute the above program, it might take a few minutes to execute. After the complete execution, you will see a similar output:

    Conclusion

    In this article, we learned How to Make a Process Monitor in Python? In this tutorial, the use of pandas is optional. The only reason we used pandas DatFrame is that we want to sort the processes according to their memory usage. psutil is a very powerful Python library.

    Using this library, you can not only retrieve the process information but also kill a process if needed. We would recommend you to go through the official documentation of psutil to know more about its usage. As psutil is a cross-platform Python library, there are many functions that are supported by one OS but not by another.

    The above program will work fine for Windows 10, but if you are a macOS or Linux user, you can see the psutil documentation if you are getting any errors.

    People are also reading:

    Leave a Comment on this Post

    0 Comments