Python subprocess.run 使用注意事项,避免出现list index out of range

在执行iOS UI 自动化专项测试的时候,在运行第一遍的时候遇到了这样的错误:

python 复制代码
2024-12-04 20:22:27 ERROR conftest pytest_runtest_makereport 106  Test test_open_stream.py::TestOpenStream::test_xxx_open_stream[iPhoneX-xxx-1-250] failed with error: list index out of range

对应客户端上的状态是:

得出判断应该是:开流失败,对应的状态没有回来,程序中没有获取到。那么当这种情况发生时如何解决上面的bug呢?看下代码:

python 复制代码
def grep_from_sandbox_log(grep_condition, iphone_model):
    # iOS沙盒目录
    log_date = datetime.now().strftime("%Y%m%d")
    mount_path = f"/Users/testmanzhang/ios_sandbox/{iphone_model}/Documents/Logs/"
    log_file_path = f"{mount_path}glazero_app_ios_{log_date}.log"

    result = None

    get_state_cmd = f"grep {grep_condition} {log_file_path}"

    if os.path.isfile(log_file_path):
        result = subprocess.run(get_state_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        if result.stderr:
            logger.error(f"grep 错误: \n {result.stderr}")
    else:
        logger.error(f"日志文件不存在: {log_file_path}")

    return result
python 复制代码
def get_dev_play_state_result(click_time, iphone_model, sn):
    grep_condition = f"'previewSuccess  deviceId = {sn}'"
    get_result = grep_from_sandbox_log(grep_condition, iphone_model)

    # 分析获取的结果
    if get_result:
        lines = result_get_success.stdout.splitlines()
        last_line = lines[-1]
        logger.info(f"最后一行唤醒成功的结果: {last_line}\n")

问题出现在grep_from_sandbox_log方法中的

python 复制代码
result = subprocess.run(get_state_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

如果结果是空的时候,返回的result是:

python 复制代码
CompletedProcess(args='truncate -s 0 /Users/testmanzhang/ios_sandbox/iPhoneX/Documents/Logs/glazero_app_ios_20241204.log', returncode=0, stdout='', stderr='')

这时候在get_dev_play_state_result方法中,对获取到的返回结果进行判断也是True,这样问题就发生了,lines其实是一个空列表,再去使用[-1]去获取数据就报错了。

python 复制代码
    if get_result:
        lines = result_get_success.stdout.splitlines()
        last_line = lines[-1]

解决这个问题要在grep_from_sandbox_log方法中对result进行处理,即对result.stdout进行处理,把处理完成后的结果返回给其他方法,例如,get_dev_play_state_result,不能直接返回result。

在grep_from_sandbox_log方法中调整一下:

python 复制代码
    if os.path.isfile(log_file_path):
        result = subprocess.run(get_state_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        if result.stderr:
            logger.error(f"grep 错误: \n {result.stderr}")
        elif result.returncode == 0 and result.stdout == '':
            logger.info(f"返回的return code为'',stdout为''")
        elif result.returncode == 0 and result.stdout != '':
            logger.info(f"返回的内容不为空,返回result.stdout的内容")
            get_result = result.stdout
相关推荐
玄同76544 分钟前
从 0 到 1:用 Python 开发 MCP 工具,让 AI 智能体拥有 “超能力”
开发语言·人工智能·python·agent·ai编程·mcp·trae
小瑞瑞acd1 小时前
【小瑞瑞精讲】卷积神经网络(CNN):从入门到精通,计算机如何“看”懂世界?
人工智能·python·深度学习·神经网络·机器学习
文件夹__iOS1 小时前
AsyncStream 进阶实战:SwiftUI 全局消息流极简实现
ios·swiftui·swift
火车叼位1 小时前
也许你不需要创建.venv, 此规范使python脚本自备依赖
python
火车叼位1 小时前
脚本伪装:让 Python 与 Node.js 像原生 Shell 命令一样运行
运维·javascript·python
L543414462 小时前
告别代码堆砌匠厂架构让你的系统吞吐量翻倍提升
大数据·人工智能·架构·自动化·rpa
孤狼warrior2 小时前
YOLO目标检测 一千字解析yolo最初的摸样 模型下载,数据集构建及模型训练代码
人工智能·python·深度学习·算法·yolo·目标检测·目标跟踪
Katecat996632 小时前
YOLO11分割算法实现甲状腺超声病灶自动检测与定位_DWR方法应用
python
玩大数据的龙威2 小时前
农经权二轮延包—各种地块示意图
python·arcgis
ZH15455891312 小时前
Flutter for OpenHarmony Python学习助手实战:数据库操作与管理的实现
python·学习·flutter