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

如何在pytest框架中用subprocess.run跨项目运行feature文件?

解决subprocess执行behave命令的FileNotFoundError问题

错误原因

你遇到的FileNotFoundError是因为subprocess.run接收args为单个字符串时,会把整个字符串当作一个完整的命令文件路径去查找,而不是拆分命令和参数。系统找不到名为behave ./features/Demo/test_requisition.feature的可执行文件,自然报错。

解决方案

方案1:拆分命令为列表(推荐,跨平台)

把命令和参数拆成列表形式传递给args,这是subprocess官方推荐的方式,避免shell解析问题,同时兼容Windows/Linux/macOS:

import subprocess
from pathlib import Path

# 修正拼写错误:fodler_path -> folder_path
folder_path = Path(__file__).parent.parent / "so2c-integration-test-framework"
# 拆分命令为列表:命令 + 参数
subprocess.run(args=["behave", "./features/Demo/test_requisition.feature"], cwd=folder_path)
print("done running")

方案2:启用shell解析(适合简单场景)

如果坚持用字符串形式,需要添加shell=True参数,让shell帮忙解析命令和参数:

import subprocess
from pathlib import Path

folder_path = Path(__file__).parent.parent / "so2c-integration-test-framework"
subprocess.run(args="behave ./features/Demo/test_requisition.feature", cwd=folder_path, shell=True)
print("done running")

注意:shell=True存在安全风险(如果命令包含不可信输入可能导致注入),仅在可控场景下使用。

额外验证步骤

  1. 确认目标目录存在:可以先打印路径并手动检查,避免拼写错误:
    print(folder_path.exists())  # 输出True表示路径有效
    
  2. 确认behave可执行:如果仍报错,可能是behave不在系统环境变量中,可改用behave的绝对路径(比如/usr/local/bin/behave或C:\PythonXX\Scripts\behave.exe)替换列表中的"behave"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:37:07