Python循环监控进程是否存在

技术分享 2025-11-24

循环监控某个进程是否存在,不存在就执行启动。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import time
import subprocess
import psutil
from datetime import datetime

def is_process_running(process_keyword):
    """检查包含指定关键字的进程是否在运行"""
    try:
        for proc in psutil.process_iter(['name', 'cmdline']):
            try:
                # 检查进程名
                if process_keyword.lower() in proc.info['name'].lower():
                    return True

                # 检查命令行
                if proc.info['cmdline']:
                    cmdline_str = ' '.join(proc.info['cmdline']).lower()
                    if process_keyword.lower() in cmdline_str:
                        return True
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                continue
    except Exception as e:
        print(f"[ERROR] 检查进程时出错: {e}")
    return False

def execute_script(script_path):
    """执行启动脚本"""
    if not os.path.exists(script_path):
        print(f"[ERROR] 脚本不存在: {script_path}")
        return False

    try:
        result = subprocess.run(
            script_path,
            shell=True,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        print(f"[INFO] 脚本执行成功")
        if result.stdout:
            print(f"[OUTPUT] {result.stdout}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"[ERROR] 脚本执行失败 (返回码: {e.returncode})")
        print(f"[ERROR OUTPUT] {e.stderr}")
        return False

def main():
    # 配置参数(请根据实际情况修改)
    PROCESS_KEYWORD = "Office"      # 要监控的进程关键字
    STARTUP_SCRIPT = "cd /opt/Seeyon/G6N/OfficeTrans && ./startup.sh"  # 启动脚本路径
    CHECK_INTERVAL = 10             # 检查间隔(秒)

    print(f"[INFO] 开始监控进程: {PROCESS_KEYWORD}")
    print(f"[INFO] 启动脚本: {STARTUP_SCRIPT}")
    print(f"[INFO] 检查间隔: {CHECK_INTERVAL}秒")

    try:
        while True:
            current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            if is_process_running(PROCESS_KEYWORD):
                print(f"[{current_time}] [INFO] 进程运行正常")
            else:
                print(f"[{current_time}] [WARNING] 进程不存在,尝试启动...")
                #execute_script(STARTUP_SCRIPT)

            time.sleep(CHECK_INTERVAL)

    except KeyboardInterrupt:
        print("\n[INFO] 监控脚本被中断")
    except Exception as e:
        print(f"[ERROR] 监控过程中发生错误: {e}")

if __name__ == "__main__":
    main()

评论 (0)

发表评论

最多500字符

验证码

暂无评论

成为第一个评论的人吧!