adb shell + python 命令

Python 调用adb shell 外部命令(subprocess,推荐,适合你现在 Appium 场景)

import subprocess

# 示例1:执行单条adb shell命令,强制关闭百度阅读
cmd = r'adb shell am force-stop com.baidu.yuedu'
result = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8")
print("标准输出:", result.stdout)
print("错误信息:", result.stderr)

# 示例2:启动百度阅读
cmd2 = r'adb shell am start -n com.baidu.yuedu/com.baidu.yuedu.splash.SplashActivity'
subprocess.run(cmd2)

# 示例3:adb截图
cmd3 = r'adb exec-out screencap -p > screen.png'
subprocess.run(cmd3, shell=True)

参数说明:

  • capture_output=True:捕获命令返回的日志
  • text=True:输出转为字符串(等价 PowerShell Out-String)
  • shell=True:管道 / 重定向命令(>、|)必须加

常用封装函数

import subprocess

def adb_shell(cmd_text):
    """封装adb shell调用,返回输出文本"""
    full_cmd = f'adb shell {cmd_text}'
    res = subprocess.run(full_cmd, capture_output=True, text=True, encoding="utf-8")
    return res.stdout, res.stderr

# 使用示例
stdout, stderr = adb_shell("am force-stop com.baidu.yuedu")
print(stdout, stderr)

stdout, stderr = adb_shell("input tap 300 600") # 点击坐标
print(stdout)
posted @ 2026-10-20 14:13  一只鹿吖  阅读(4)  评论(0)    收藏  举报