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

根据Python脚本的不同输出结果执行对应脚本的实现方法

根据Python脚本的不同输出结果执行对应脚本的实现方法

嘿,我来帮你搞定这个需求!你想要根据那段API请求代码的输出结果,自动运行对应的test1.py或者test2.py对吧?这里有两种简单靠谱的方法,你可以根据自己的习惯选:

方法一:在原Python脚本内部直接处理

这种方式不用额外写其他脚本,直接在现有代码里扩展逻辑就行,用Python的subprocess模块来启动测试脚本。

首先,你可以调整原函数的返回值(或者直接在逻辑里标记状态),然后根据结果调用对应的脚本:

import requests
import logging
import subprocess

# 初始化日志配置(确保输出能正常显示)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def create_group(url, group):
    try:
        response = requests.post(
            url, json=group, headers=self._headers, auth=self._auth
        )
        logger.info(f"API Response: {response.text}")
        # 标记成功状态,对应你说的"BLACK"输出
        print("BLACK")
        return True
    except requests.exceptions.RequestException as e:
        logger.error(
            f"Failed to create group '{group['groupName']}'. "
            f"Exception: {str(e)}"
        )
        # 标记失败状态,对应"WHITE"输出
        print("WHITE")
        return False

# 主执行逻辑
if __name__ == "__main__":
    # 替换成你的实际API地址和group参数
    target_url = "https://your-api-endpoint.com"
    target_group = {"groupName": "my-test-group"}
    
    # 调用创建组的函数
    success = create_group(target_url, target_group)
    
    # 根据状态执行对应脚本
    if success:
        # 运行test1.py,若脚本不在当前目录,写完整路径比如"/home/user/test1.py"
        subprocess.run(["python", "test1.py"], check=True)
    else:
        subprocess.run(["python", "test2.py"], check=True)

小提示:

  • 如果你的系统默认Python版本是3,记得把python换成python3,避免版本冲突
  • 如果test1.py/test2.py需要传入参数,直接在列表里加就行,比如subprocess.run(["python", "test1.py", "--env", "dev"])

方法二:用Shell脚本捕获输出后判断(不修改原Python脚本)

如果你不想改动现有的Python代码,可以写一个简单的bash脚本,捕获原脚本的输出内容,再决定运行哪个测试脚本。

假设你的原脚本运行时会把BLACK或WHITE输出到控制台(如果用logger输出,默认是到stderr,需要重定向到stdout),创建一个名为run_tests.sh的脚本:

#!/bin/bash

# 运行原Python脚本,同时把stderr重定向到stdout(适配logger输出)
script_output=$(python your_original_script.py 2>&1)

# 判断输出中是否包含关键词
if echo "$script_output" | grep -q "BLACK"; then
    echo "检测到成功输出,运行test1.py..."
    python test1.py
elif echo "$script_output" | grep -q "WHITE"; then
    echo "检测到失败输出,运行test2.py..."
    python test2.py
else
    echo "未识别的输出内容:$script_output"
    exit 1
fi

然后给脚本加执行权限:

chmod +x run_tests.sh

之后直接运行这个脚本就行:

./run_tests.sh

小提示:

  • 同样,如果用Python3,把脚本里的python换成python3
  • 如果BLACK/WHITE是唯一的关键词,这个方法会很稳定;如果输出里有其他相同字符串,可能需要调整判断逻辑,比如用精确匹配grep -q "^BLACK$"

备注:内容来源于stack exchange,提问作者Michał Pieniak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 10:49:30