第一部分:基础语法
1. 变量、字符串、列表、字典
s = "adb shell input keyevent 4" print(s) #列表,存多条adb命令 cmd_list = ["打开app","截图","返回"] print(cmd_list[0]) #字典,存测试结果 result = {"case":"切换信号源", "status":"pass"} print(result["status"])

2. 判断 if‑else
ret_code = 0 if ret_code ==0: print("执行成功") else: print("执行失败")

3. 循环 for /while
#循环执行3次截图 for i in range(3): print(f"第{i}次截图") count=0 while count<3 count = count+1 print(count)

4. 函数 def
def run_adb(command): print("执行命令:",command)
#后面在这里补subprocess逻辑 return 0 run_adb("adb devices")

第二部分 核心模块【重中之重】
1.subprocess:调用 adb 命令。
重点:拿到返回码、标准输出、错误输出
import subprocess def run_adb(cmd_list): """ cmd_list:列表形式命令,例如 ["adb","shell","input","keyevent","KEYCODE_BACK"] return 返回码,标准输出,错误输出 """ res = subprocess.run(cmd_list, capture_output=True, text=True) return res.returncode, res.stdout, res.stderr #模拟返回按键 code,out,err = run_adb(["adb","shell","input","keyevent","KEYCODE_BACK"]) if code == 0: print("按键成功") else: print(f"执行失败,错误信息:{err}")
2. 异常捕获 try‑except(自动化脚本必备)
adb 设备断开、命令出错不能让整个脚本直接崩溃,要捕获异常。
import subprocess def run_adb(cmd_list): try: res = subprocess.run(cmd_list, capture_output=True, text=True,timeout=10) return res.returncode, res.stdout, res.stderr except Exception as e: print(f"脚本发生异常:{e}") return -1,"",str(e) code,out,err = run_adb(["adb","shell","input","keyevent","KEYCODE_BACK"]) print(code)
3. 文件读写:保存截图信息、保存日志
#写文件 w覆盖;a追加 with open("test_log.txt","a",encoding="utf‑8") as f: f.write("本次测试:切换HDMI\n")
4. logging 模块:规范打印脚本日志
import logging logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", filename="run.log" ) logging.info("脚本开始执行") logging.error("用例执行失败")
5. time 模块,等待、简单重试逻辑
import time time.sleep(2) #固定等待2秒 #简易重试:失败最多重试2次 def run_with_retry(cmd, retry=2): for i in range(retry+1): code,out,err = run_adb(cmd) if code ==0: return code,out,err print(f"第{i+1}次执行失败,准备重试") time.sleep(1) return -1,"","多次执行失败"
第三部分 uiautomator2 APP 自动化
安装
pip install --pre uiautomator2 python -m uiautomator2 init
例子
import uiautomator2 as u2 import time d = u2.connect() #usb连接手机 d.app_start("com.android.settings") #启动设置 d(text="蓝牙").wait(timeout=5) #等待元素出现 d(text="蓝牙").click() d.screenshot("bluetooth.png") d.app_stop("com.android.settings")
第四部分 pytest 基础
学会写用例、断言、执行脚本即可
安装:
pip install pytest新建
test_demo.pydef test_adb_demo(): code,out,err = run_adb(["adb","devices"]) assert code == 0,"adb执行失败" def test_click_back(): code,out,err = run_adb(["adb","shell","input","keyevent","KEYCODE_BACK"]) assert code ==0
命令行执行:
pytest test_demo.py -v
浙公网安备 33010602011771号