How to Make a Process Monitor in Python

Published on Aug. 22, 2023, 12:15 p.m.

To create a process monitor in Python, you can use the psutil library. Here are the general steps:

  1. Install psutil library using pip:
pip install psutil
  1. Import the necessary modules:
import psutil
import time
  1. In a while loop, use the pid_exists method of the psutil library to check whether a given process ID exists or not.
pid = 

while True:
 if not psutil.pid\_exists(pid):
 print("Process has terminated.")
 break
 time.sleep(1)

In this example, the loop will run indefinitely and check whether the specified process ID exists every second. If the process has terminated, it will print a message and then break out of the loop.

You can add additional functionality to the while loop depending on your specific needs, such as sending an email notification or restarting the process if it terminates.

To use the psutil library to find a process by name in Python

To use the psutil library to find a process by name in Python, you can use the process_iter() method of the psutil library to iterate through all running processes and then filter the list based on the name attribute. Here’s an example:

import psutil

# Find the process name you want to filter
process_name = "example_process"

# Iterate through all running processes
for proc in psutil.process_iter(['name']):
    # Check whether the process name matches
    if proc.info['name'] == process_name:
        # Do something with the matched process
        print(f"Process with name {process_name} found! PID: {proc.pid}")

In this example, we first specify the process name that we want to filter for. Then, we use process_iter() to iterate through all running processes while requesting only the name attribute for each process. We then check whether the name attribute of each process matches our target process name. If a match is found, we can then perform any desired action with the process, such as accessing its PID or terminating it.

Tags: