🔍 Code Extractor

function check_service_process

Maturity: 44

Checks if a specific Python process (email forwarder service running 'python src/main.py') is currently active on the system by parsing the output of the 'ps aux' command.

File:
/tf/active/vicechatdev/email-forwarder/service_status.py
Lines:
11 - 21
Complexity:
simple

Purpose

This function is used to monitor and verify whether the email forwarder service is running. It searches through all running processes to find one that matches the pattern 'python src/main.py', which is useful for service health checks, preventing duplicate instances, or implementing restart logic. The function filters out grep processes to avoid false positives when the search itself appears in the process list.

Source Code

def check_service_process():
    """Check if the email forwarder process is running."""
    try:
        result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
        lines = result.stdout.split('\n')
        for line in lines:
            if 'python src/main.py' in line and 'grep' not in line:
                return True, line.strip()
        return False, None
    except:
        return False, None

Return Value

Returns a tuple of two elements: (bool, str or None). The first element is True if the email forwarder process is found running, False otherwise. The second element is the full process line as a string (stripped of whitespace) if the process is found, or None if not found or if an exception occurs. The process line typically contains information like PID, CPU usage, memory usage, and the full command.

Dependencies

  • subprocess

Required Imports

import subprocess

Usage Example

import subprocess

def check_service_process():
    """Check if the email forwarder process is running."""
    try:
        result = subprocess.run(['ps', 'aux'], capture_output=True, text=True)
        lines = result.stdout.split('\n')
        for line in lines:
            if 'python src/main.py' in line and 'grep' not in line:
                return True, line.strip()
        return False, None
    except:
        return False, None

# Example usage
is_running, process_info = check_service_process()
if is_running:
    print(f"Email forwarder is running: {process_info}")
else:
    print("Email forwarder is not running")

# Example for service monitoring
if not is_running:
    print("Service is down, attempting restart...")
    # Add restart logic here

Best Practices

  • This function only works on Unix-like systems (Linux, macOS) that support the 'ps aux' command. It will not work on Windows.
  • The bare 'except' clause catches all exceptions, which may hide important errors. Consider catching specific exceptions like subprocess.SubprocessError for production code.
  • The function searches for the exact string 'python src/main.py', so it won't detect the process if it's started with a different Python interpreter (e.g., 'python3 src/main.py') or from a different directory.
  • For more robust process checking, consider using the 'psutil' library which provides cross-platform process management capabilities.
  • The function may return false positives if other processes have 'python src/main.py' in their command line arguments or environment variables.
  • Consider adding timeout parameters to subprocess.run() to prevent hanging if the ps command takes too long.
  • For production systems, implement proper logging instead of silently returning False on exceptions.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function check_service_stats 63.0% similar

    Validates that the email forwarding service can retrieve operational statistics by instantiating an EmailHandler and calling its get_stats() method.

    From: /tf/active/vicechatdev/email-forwarder/test_e2e.py
  • function main_v55 60.3% similar

    Performs a comprehensive status check of an email forwarder service, verifying process status, port availability, SMTP communication, and configuration settings.

    From: /tf/active/vicechatdev/email-forwarder/service_status.py
  • function start_service 51.9% similar

    Orchestrates the startup sequence for an email forwarder service by validating environment, dependencies, configuration, and project structure before launching the main application.

    From: /tf/active/vicechatdev/email-forwarder/run_service.py
  • function main_v51 51.5% similar

    Entry point function that validates the working directory and starts an email forwarding service.

    From: /tf/active/vicechatdev/email-forwarder/run_service.py
  • function check_virtual_env 49.8% similar

    Detects whether the Python interpreter is running inside a virtual environment by checking system attributes.

    From: /tf/active/vicechatdev/email-forwarder/run_service.py
← Back to Browse