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

使用Command::new("echo")时出现「program not found」错误求助

问题原因与解决办法

问题根源

你的代码在Windows系统上运行时找不到echo程序,因为echo是Windows CMD的内置命令,并非独立的可执行文件(不存在单独的echo.exe),而Command::new()只能直接调用独立的可执行程序,因此会触发"program not found"错误。

修正后的代码

将调用方式改为通过cmd.exe执行内置命令:

use std::process::Command;

fn main() {
    let output = Command::new("cmd")
        .args(["/c", "Hello world"])
        .output()
        .expect("Failed to execute command");

    assert_eq!(b"Hello world\r\n", output.stdout.as_slice());
}

关键改动说明

  • 用cmd.exe作为执行主体,参数/c表示执行后续命令后立即退出CMD进程
  • Windows系统下命令输出的换行符是\r\n(CRLF格式),因此断言内容需要调整为b"Hello world\r\n",与实际输出匹配

如果是在Linux/macOS环境下,echo是独立的可执行文件(通常路径为/bin/echo),你的原代码可以正常运行,但Windows环境必须采用上述方式调用内置命令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 06:29:58