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

Python脚本运行Newman报错:文件未找到及npm无法识别Newman的解决方法

解决Python脚本运行Newman的路径问题

问题分析

  • 直接调用newman命令提示"File not found":系统环境变量PATH未包含Newman可执行文件的所在目录,导致subprocess无法定位该命令。
  • 用npm.cmd直接带newman参数报错:npm命令格式错误,不能直接将newman作为参数传给npm.cmd,需通过npm exec来调用全局或局部安装的包命令。

解决方案

方案1:直接使用Newman的绝对路径

先找到Newman可执行文件的实际路径:

  • 全局安装的Newman,Windows下通常路径为C:\Users\<你的用户名>\AppData\Roaming\npm\newman.cmd,Linux/macOS下为/usr/local/bin/newman
  • 局部安装的Newman,路径在项目目录下的node_modules/.bin/newman.cmd(Windows)或node_modules/.bin/newman(Linux/macOS)

修改Python代码,替换为Newman的绝对路径:

try:
    # 替换为你实际的newman可执行文件绝对路径
    process = subprocess.Popen(
        ['C:\\Users\\YourUsername\\AppData\\Roaming\\npm\\newman.cmd', 'run', '<真实集合路径>', '--export-collection', '<真实导出文件路径>'],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    print(f"Newman started. PID: {process.pid}")
    stdout, stderr = process.communicate()  # 用communicate避免输出缓冲区满导致进程挂起
    print(f"Command completed with return code {process.returncode}")
    print("Stdout:", stdout.decode('utf-8'))
    print("Stderr:", stderr.decode('utf-8'))
except Exception as e:
    print(e)

方案2:用npm exec执行Newman

如果不想手动查找绝对路径,可通过npm exec命令调用Newman,全局/局部安装场景均适用:

try:
    process = subprocess.Popen(
        ['C:\\Program Files\\nodejs\\npm.cmd', 'exec', 'newman', 'run', '<真实集合路径>', '--export-collection', '<真实导出文件路径>'],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )
    print(f"Newman started. PID: {process.pid}")
    stdout, stderr = process.communicate()
    print(f"Command completed with return code {process.returncode}")
    print("Stdout:", stdout.decode('utf-8'))
    print("Stderr:", stderr.decode('utf-8'))
except Exception as e:
    print(e)

方案3:将Newman路径添加到系统PATH

  1. 找到Newman所在目录(比如全局安装的C:\Users\<你的用户名>\AppData\Roaming\npm)
  2. 将该目录添加到系统环境变量PATH中
  3. 重启Python运行环境,之后即可直接使用newman命令执行脚本

额外提示

  • 务必将代码中的<真实集合路径>和<真实导出文件路径>替换为服务器上的实际路径,Windows路径需用\\分隔或使用原始字符串r"路径"。
  • 优先使用process.communicate()替代process.wait(),避免因输出缓冲区溢出导致进程卡住。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 17:03:24