Python实现检查安卓设备是否运行monkey并杀掉进程

Python实现检查安卓设备是否运行monkey并杀掉进程

实测有效:

import subprocess

udId = "ASDF"

def run_command(cmd):
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    output, error = process.communicate()
    return output.decode().strip()


def check_and_kill_pid(udId):
    #read
    run_command(f'adb -s {udId} shell ps > shellps.log')

    #check
    with open('shellps.log', 'r') as file:
        for line in file:
            if 'com.android.commands.monkey' in line:
                apk_pin = line.split()[1]
                break
        else:
            apk_pin = None

    #kill
    if apk_pin:
        print(f"Monkey process PID : {apk_pin}")
        run_command(f'adb -s {udId} shell kill {apk_pin}')
        print("Monkey test end.")
    else:
        print("android device not run monkey test.")



if __name__ == '__main__':
    check_and_kill_pid(udId)