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

在Rust中调用WSL bash执行命令报错:找不到指定路径

问题解决方法

错误原因

你误用了Command::new的用法:这个方法的参数只能是单独的可执行文件路径,不能是包含参数的完整命令字符串。当你把C:\Windows\System32\bash.exe /mnt/xxx/test.sh整个传给它时,系统会尝试寻找一个名为bash.exe /mnt/xxx/test.sh的可执行文件,自然找不到,因此抛出路径不存在的错误。而PowerShell会自动拆分命令主体和参数,所以直接运行打印的字符串能成功执行。

修复后的代码

将可执行文件路径和参数分开处理,用arg方法传递脚本路径参数:

fn main() {
    use std::process::{Command, Stdio};

    let mut dir = std::env::current_dir().unwrap();
    dir.push("scripts");

    // 转换为WSL兼容的路径格式
    let wsl_path = dir.display()
        .to_string()
        .to_lowercase()
        .replace(':', "")
        .replace('\\', "/");
    let script_path = format!("/mnt/{}/test.sh", wsl_path);
    
    println!("C:\\Windows\\System32\\bash.exe {}", script_path);

    Command::new("C:\\Windows\\System32\\bash.exe")
        .arg(script_path)
        .stdout(Stdio::piped())
        .spawn()
        .and_then(|p| p.wait_with_output())
        .unwrap();
}

额外优化建议

  • 可以用更安全的路径转换方式替代手动字符串替换,避免格式错误:
    let dir_str = dir.as_os_str().to_str().unwrap();
    let (drive, rest) = dir_str.split_once(':').unwrap();
    let wsl_path = format!("/mnt/{}{}", 
        drive.to_ascii_lowercase(),
        rest.replace('\\', "/")
    );
    
  • 避免滥用unwrap(),建议用match或if let处理错误,提升程序健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 15:00:58