Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check any script is running in linux using Python?
The psutil module in Python helps us retrieve information about processes currently running on our Linux system. This is essential for monitoring and managing scripts programmatically.
What is a Script?
A script is a set of instructions written in a programming language and executed by the computer. Scripts help us perform repetitive tasks efficiently, from simple file operations to complex system administration. In Linux, scripts are typically executed through command line using shell interpreters like Bash or Python interpreters. These scripts can be scheduled using cron or systemd timers.
Method 1: Using psutil Module
The psutil library provides cross-platform process monitoring capabilities. First, install it if not already available ?
pip install psutil
Example
Here's how to check if a specific script is running ?
import psutil
def is_process_running(script_name):
"""Check if a script is currently running"""
for process in psutil.process_iter(['name', 'cmdline']):
try:
# Check both process name and command line arguments
if process.info['name'] and script_name in process.info['name']:
return True
if process.info['cmdline']:
cmdline_str = ' '.join(process.info['cmdline'])
if script_name in cmdline_str:
return True
except (psutil.NoSuchProcess, psutil.AccessDenied):
# Process may have terminated or access denied
continue
return False
# Test the function
script_name = 'test_script.py'
if is_process_running(script_name):
print(f'The script "{script_name}" is running.')
else:
print(f'The script "{script_name}" is not running.')
The script "test_script.py" is not running.
Method 2: Using subprocess Module
The subprocess module is part of Python's standard library, so no installation is needed. It executes system commands and captures their output ?
Example
Using the ps command to check running processes ?
import subprocess
def check_script_with_ps(script_name):
"""Check if script is running using ps command"""
try:
# Execute ps command to list all processes
ps_output = subprocess.check_output(["ps", "aux"], universal_newlines=True)
# Search for script name in process list
if script_name in ps_output:
print(f"The script '{script_name}' is running")
return True
else:
print(f"The script '{script_name}' is not running")
return False
except subprocess.CalledProcessError as e:
print(f"Error executing ps command: {e}")
return False
# Test with Python script
script_name = "sample.py"
check_script_with_ps(script_name)
The script 'sample.py' is not running
Example
Checking for PHP scripts using the same approach ?
import subprocess
def is_script_active(script_name):
"""Enhanced script checker with better error handling"""
try:
# Use pgrep for more precise process matching
result = subprocess.run(
["pgrep", "-f", script_name],
capture_output=True,
text=True
)
if result.returncode == 0 and result.stdout.strip():
print(f"Script '{script_name}' is running (PID: {result.stdout.strip()})")
return True
else:
print(f"Script '{script_name}' is not running")
return False
except FileNotFoundError:
# Fallback to ps if pgrep not available
print("pgrep not found, using ps command...")
return check_script_with_ps(script_name)
# Test with PHP script
php_script = "sample.php"
is_script_active(php_script)
Script 'sample.php' is not running
Comparison
| Method | Advantages | Best For |
|---|---|---|
psutil |
Cross-platform, detailed process info | Complex monitoring applications |
subprocess |
No external dependencies, native Linux tools | Simple checks, shell scripting |
Conclusion
Use psutil for robust cross-platform script monitoring with detailed process information. Use subprocess with Linux commands like ps or pgrep for simple checks without external dependencies. Both methods effectively detect running scripts in Linux environments.
