How to check if a process is still running using Python on Linux?

Check Process Is Still Running Using Python On Linux

In Linux, the process is executing an instance of a running program. It represents a particular running program or command. When you execute a program, the operating system creates a process to run that program. Each process has its unique process ID (PID). You can use commands like ‘ps’, and ‘top’ to see running process details.

Python can be used to check if a process is running using libraries like ‘psutil’ and modules like ‘subprocess’. The ‘psutil’ library allows iterating over running processes to find a specific one, while the ‘subprocess’ module can leverage system commands like ‘pgrep’ for process monitoring. Both methods are essential for efficient system management, preventing duplicate processes, and ensuring dependencies are met.

For example, use the ‘top’ command to get details of running processes.

Top Cmd

Here by using the ‘top’ command, you can see all the details of running processes with their PID.


Python Approach to Process Monitoring

Also read: How to Create Python3 Aliases in Windows and Ubuntu/Linux

We can check whether a process is running using some Python libraries.

Monitoring Processes with Python’s psutil Library

To use the Python ‘psutil’ library, you have to install the ‘psutil’ library using the following command:

pip install psutil
Psutil

The ‘psutil‘ is successfully installed.

Now to check that the process is running, first create a Python file using the vi text editor by using the following command.

vi check_process.py

Here we create a Python file named ‘check_process.py‘. Press ‘i’ for insert mode and now start typing. The Python script to check if the process is running is given below:

import psutil

def process_status(process_name):
    for process in psutil.process_iter(['pid', 'name']):
        if process.info['name'] == process_name:
            return True
    return False

# Example
process_name = "sshd"
if process_status(process_name):
    print(f"The process {process_name} is running.")
else:
    print(f"The process {process_name} is not running.")

Now press Esc type ‘:wq!’ and press enter to save and exit. This writes the changes and quits the editor. Here we use process ‘sshd’, you can replace the process_name ‘sshd’ with your actual process name.

Psutil Eg1 1

The first line ‘import psutil‘, imports the ‘psutil‘ library. After that, we define a function as process_status. This function takes process_name as an argument, process_name is the name of the process you want to check for.

The line ‘psutil.process_iter’ is used to iterate over the running processes on the system, retrieving information like PID and process name. The if loop checks if the process is running.

If the name matches with the process name then it returns true which means the process is running and if the loop completes without finding a matching process, the function returns false.

The example part simply uses the defined function process_status to check process is running or not. We use the process name ‘sshd’. In the given example, we check for the ‘sshd’ process. The code then prints whether the process is running or not.

Output:

Now you can run the Python script using the following command:

python check_process.py

Here you can replace check_process.py with the actual name of your Python script.

Sshd Op

The output is ‘The process sshd is running’.


Let’s see another example of not running process:

Psutil Eg 3

This is an example where we use the hello.py process to check if it running or not.

Psutil Op 1

The hello.py process is not running that’s why it prints the output as ‘The process hello.py is not running’.


Also read: Most Popular Python Libraries Used In Online Gaming

Python’s Subprocess Module for Process Monitoring

Now let’s see how to check if the process is running or not using the ‘subprocess’ module. The Python script to check if the process is running is given below:

import subprocess

def process_status(process_name):
    try:
        subprocess.check_output(["pgrep", process_name])
        return True
    except subprocess.CalledProcessError:
        return False

# Example
process_name = "systemd"
if process_status(process_name):
    print(f"Yes, the process {process_name} is running.")
else:
    print(f"No, the process {process_name} is not running.")

Here we use process ‘systemd’, you can replace the process_name ‘systemd’ with the actual name of the process you want to check.

Subprocesss Eg 1

First, we import the subprocess module using the ‘import subprocess’ line. Then we define a function as ‘process_status’ to check if the process is running. This function takes the ‘process_name’ as an argument representing the process name.

The ‘try‘ and ‘except‘ block is used for exception handling. The ‘check_output’ function is used to run the ‘pgrep’ command. ‘pgrep’ is a command line that searches for the process by its name and prints the process ID (PID). If the process is found it returns True and if the process is not found it returns False.

The example part simply uses the defined function ‘process_status‘ to check process is running or not. We use the process name ‘systemd’. In the given example, we check for the ‘systemd‘ process. The script then prints whether the process is running or not.

Output:

Subprocesss Op 1

The output is ‘Yes, the process systemd is running’

In this article, we learn how to check if the process is running or not using Python. Here we create a Python script first by using the ‘psutil’ library and then by using the ‘subprocess‘ module.

Checking whether the process is running is important for tasks such as checking dependencies, preventing duplicates, etc. So before interacting with the process, you may want to check dependencies. Also, you might want to ensure that only one instance of a particular process is running at a time. How could these techniques be applied in your current projects?

References:

https://unix.stackexchange.com/questions/110698/how-to-check-which-specific-processes-python-scripts-are-running