【问题标题】:Invoking shell scripts on Windows under MSYS using Command在 MSYS 下使用 Command 在 Windows 上调用 shell 脚本
【发布时间】:2015-04-27 18:17:46
【问题描述】:

我试图在 MSYS2 环境中的 Windows 7 上调用 Rust (1.0 beta 3) 中的命令,但我不明白该怎么做。

假设您的主文件夹中有一个名为 myls 的非常简单的脚本:

#!/bin/bash

ls

现在在 Rust 中创建一个调用脚本的简单程序:

use std::process::Command;
use std::path::Path;

fn main() 
{
    let path_linux_style = Path::new("~/myls").to_str().unwrap();
    let path_win_style   = Path::new("C:\\msys64\\home\\yourname\\myls").to_str().unwrap();

    let out_linux = Command::new(path_linux_style).output();
    let out_win   = Command::new(path_win_style).output();

    match out_linux
    {
        Ok(_)  => println!("Linux path is working!"),
        Err(e) => println!("Linux path is not working: {}", e)
    }

    match out_win
    {
        Ok(_)  => println!("Win path is working!"),
        Err(e) => println!("Win path is not working: {}", e)
    }
}

现在,如果你尝试执行它,你会得到以下输出:

Linux path is not working: The system cannot find the file specified.
 (os error 2)
Win path is not working: %1 is not a valid Win32 application.
 (os error 193)

所以我无法在 MSYS 环境中调用任何命令。 我该如何解决?

编辑: 我注意到如果我调用一个可执行文件,问题就不会发生,所以它似乎与调用 bash 脚本有关。无论如何,这很烦人,因为它使编译项目依赖于外部 C/C++ 代码(需要启动 configure 脚本)很难开始工作。

【问题讨论】:

    标签: path command rust msys


    【解决方案1】:

    Windows 示例不起作用,因为 Windows 不是 Unix。在类 Unix 系统上,脚本开头的 #! 被识别,它调用给定路径的可执行文件作为解释器。 Windows 没有这种行为;即使这样,它也无法识别/bin/bash 的路径名,因为该路径名是 msys2 模拟的,它不是本机路径名。

    相反,您可以使用 msys2 shell 显式执行您想要的脚本,方法是执行以下操作(根据需要更改路径,我安装了 msys32,因为它是 32 位 VM)

    let out_win   = Command::new("C:\\msys32\\usr\\bin\\sh.exe")
                                .arg("-c")
                                .arg(path_win_style)
                                .output();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      相关资源
      最近更新 更多