How to check any script is running in linux using Python?


The psutil module in Python helps us to retrieve information about the processes that are currently running in our local system.

What is a script?

AScript is a set of instructions that are written in programming language and executed in the computer. We can perform a variety of simple to complex repetitive tasks within less time. In Linux, the scripts are often executed through the command line using the shell interpreters like Bash or python. These scripts can also be scheduled to run at a particular times using the cron or systemd.

Installing psutil module

To work with the psutil module, firstly we have to check whether the module is installed or not. If not, we have to install by using the below code.

pip install psutil

Example

In the following example, we are passing a script (file name) to the user defined function is_process_running(). If the script is currently running, this function returns true. If not, false.

import psutil
def is_process_running(name):
    for process in psutil.process_iter(['name']):
        if process.info['name'] == name:
            return True
    return False
if is_process_running('script.py'):
    print('The script is running.')
else:
    print('The script is not running.')

Output

The script is not running.

Installing Sub process.run module

We have one more way to check whether the script is running in Linux or not; using the sub process.run module. But first, we have to install the sub process.run module in the python environment.

pip install subprocess.run

Example

In this example, we will check whether the script is running in the Linux or not by using the sub process module. We will execute the below code in command line.

import subprocess
script_name = "sample.py"
ps_output = subprocess.check_output(["ps", "-ef"])
ps_lines = ps_output.decode("utf-8").split("\n")
for line in ps_lines:
    if script_name in line:
        print("The script is running")
        break
else:
    print("The script is not running")

Output

The following is the output of subprocess to check whether the process is running or not.

The script is not running

Example

Let’s see another example to check the script of php is running or not in the Linux using the sub process module.

import subprocess
script_name = "sample.php"
ps_output = subprocess.check_output(["ps", "-ef"])
ps_lines = ps_output.decode("utf-8").split("\n")
for line in ps_lines:
    if script_name in line:
        print("The script is running")
        break
else:
    print("The script is not running")

Output

The following is the output of the sub process module of the python language.

The script is not running

Updated on: 09-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements