Open In App

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

Last Updated : 03 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Python is a strong and exponentially growing programming language in the present day. There is a multiple-way to check which script is running in the background of a Linux environment. One of them is using the subprocess module in python. Subprocess is used to run new programs through Python code by creating new processes. In this article, we are going to see how to check any script is running in the background Linux using Python.

Requirement :

  • Python >=2.7, >= 3.0
  • pip

Installation of Subprocess :

pip install subprocess.run

We will use subprocess.checkout() methods to get all the running processes.

Syntax : subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)

This run command with argument and return output.

stderr=subprocess.STDOUT is used to capture standard error in the result.

Example 1 :

In the below code we will get all the py script running in the background Linux

Python3




import subprocess
  
  
pytonProcess = subprocess.check_output("ps -ef | grep .py",shell=True).decode()
pytonProcess = pytonProcess.split('\n')
  
for process in pytonProcess:
    print(process)


Output :

Example 2 :

In the below example we will check whether a particular script is running in background

Python3




import subprocess
  
  
pytonProcess = subprocess.check_output("ps -ef | grep test.py",shell=True).decode()
pytonProcess = pytonProcess.split('\n')
  
for process in pytonProcess:
    print(process)


Output :

Example 3 :

In the below code we will get all the PHP script running in background Linux.

Python3




import subprocess
  
  
pytonProcess = subprocess.check_output("ps -ef | grep .php",shell=True).decode()
PHPProcess = pytonProcess.split('\n')
  
for process in PHPProcess:
    print(process)


Output :



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads