这段代码实现了一个进程监控和重启的功能。主要包括以下几个步骤:

  1. check_process() 函数:通过执行 adb shell ps 命令获取当前设备上是否存在指定进程(YxwAiAudioDemo)。如果存在,返回进程状态;否则返回空。

  2. start_run() 函数:循环执行以下操作:

    a. 调用 check_process() 函数检查进程状态。如果状态正常,等待 5 秒后继续进行下一次循环;如果状态异常,记录异常信息到文件中,并等待 5 秒后继续进行下一次循环。

    b. 如果进程状态异常,执行 adb reboot 命令重启设备,并等待 60 秒。

    c. 执行启动脚本,启动指定进程(run.sh),并等待 60 秒。

  3. 创建并启动两个线程:一个线程用于执行 check_process() 函数,另一个线程用于执行 start_run() 函数。

此外,代码还使用了一些 Python 的标准库和模块,如 subprocesstimereosdatetime 等。其中,subprocess 模块用于执行系统命令;time 模块用于时间处理;re 模块用于正则表达式处理;os 模块用于文件和目录操作;datetime 模块用于日期和时间处理。

代码示例:

import subprocess
import time
import re
import os
import datetime

from threading import Thread


def check_process():
    data_dir = r'D:\python-jiaoben\性能测试\内存监控\0412\'
    if not os.path.exists(data_dir):
        os.makedirs(data_dir)

    file = open(data_dir + '进程监控.txt', 'a', encoding='utf-8')
    file.write('check status \n')
    file.close()

    p1 = subprocess.Popen('adb shell ps | grep YxwAiAudioDemo', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    data = p1.stdout.read()
    print(str(data))
    file = open(data_dir + '进程监控.txt', 'a', encoding='utf-8')
    file.write(str(data) + '\n')
    file.close()
    # print(re.findall('/aispeaker/YxwAiAudioDemo -base /aispeaker', str(data)))
    status = re.findall('/Gree/YxwAiAudioDemo -base /Gree', str(data))
    return status


def start_run():

    while True:

        if check_process():
            print('status is ok!')
            time.sleep(5)
            continue
        else:
            data_dir = r'D:\python-jiaoben\性能测试\内存监控\0412\'
            if not os.path.exists(data_dir):
                os.makedirs(data_dir)

            file = open(data_dir + '进程监控.txt', 'a', encoding='utf-8')
            file.write('进程未获取到: ' + str(datetime.datetime.now()) + '\n')
            file.close()
            time.sleep(5)

        cmd = 'adb reboot'
        os.system(cmd)
        time.sleep(60)

        print('start')
        p2 = subprocess.Popen('adb shell /etc/init.d/jd_ui stop && echo 1 > /sys/xfocus/outer_pa/mute && cd Gree && chmod 777 run.sh && ./run.sh', stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        time.sleep(60)


# thread_check = Thread(target=check_process)
# thread_check.start()


thread_start = Thread(target=start_run)
thread_start.start()

注意事项:

  • 确保 Android 设备已连接到电脑,并且 adb 命令可用。
  • 修改代码中的进程名、启动脚本路径和数据存储路径,以适应实际情况。
  • 建议使用虚拟环境或独立的 Python 环境运行该脚本,避免影响其他程序。
Python 进程监控与重启脚本:使用 adb 命令实现自动重启功能

原文地址: https://www.cveoy.top/t/topic/nwCF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录