You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ADB命令输出赋值给Robot Framework变量并对比值?

解决Robot Framework中通过ADB命令获取设备ID的问题

问题原因

  1. Run Process关键字默认返回的是ProcessResult对象,而非直接的命令输出内容,所以直接打印会显示<result object with rc 0>。
  2. 你添加.stdout后返回空值,是因为原命令的正则匹配在shell环境中存在兼容性问题,且未过滤adb devices输出的标题行List of devices attached,导致未匹配到有效内容。

方案1:调整管道命令并正确提取输出

修改命令逻辑,先过滤标题行,再用更可靠的正则匹配设备ID,同时处理输出的空白字符:

*** Variables ***
#WIN PORT BELOW
#${SERIAL_PORT}    COM3
#MAC path below
${SERIAL_ID}      178c5226

*** Test Cases ***
Test Device Serial Number
    [Documentation]  Run the adb shell and get device id/serial num and compare
    [Tags]  Smoke
    ${result} =  Run Process  adb devices | grep -v 'List' | grep -o '^[a-f0-9]\+'  shell=True
    ${actual} =  Evaluate  ${result.stdout}.strip()
    Should Be Equal     ${actual}    ${SERIAL_ID}

方案2:无需管道,用Robot Framework原生关键字处理输出

如果管道命令容易出问题,可先获取完整输出,再用RF字符串处理关键字提取设备ID:

*** Variables ***
#WIN PORT BELOW
#${SERIAL_PORT}    COM3
#MAC path below
${SERIAL_ID}      178c5226

*** Test Cases ***
Test Device Serial Number
    [Documentation]  Run the adb shell and get device id/serial num and compare
    [Tags]  Smoke
    ${result} =  Run Process  adb devices  shell=False
    # 分割输出为行列表,取第二行(跳过标题行)
    ${output_lines} =  Split To Lines  ${result.stdout}
    # 分割第二行的空格,取第一个元素即为设备ID
    ${actual} =  Split String  ${output_lines[1]}  separator=SPACE
    Should Be Equal     ${actual[0]}    ${SERIAL_ID}

关键说明

  • ProcessResult对象属性:该对象包含stdout(标准输出)、stderr(错误输出)、rc(返回码,0表示执行成功),必须通过这些属性获取具体内容。
  • 正则匹配调整:原命令的\b单词边界在不同shell的grep版本中支持不一致,换成^[a-f0-9]\+匹配行首的设备ID更可靠。
  • 空白字符处理:命令输出通常包含换行或空格,用.strip()去除首尾空白,避免比对时因格式问题不相等。

内容的提问来源于stack exchange,提问作者Shahboz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 04:10:26