std :: process :: command无法在macOS上运行hdiutil(挂载失败 - 没有这样的文件或目录)但是在终端中运行时该命令工作正常

问题描述 投票:-2回答:1

hdiutils,当输入正确的路径到有效文件时,返回error 2, no such file or directory。当我用" "连接命令数组的索引时,打印它们,复制它们并在终端中运行确切的字符串,它工作正常。

这是编辑的函数,仅包含相关位。为了重现我的错误,您需要一个位于~/Downloads/StarUML.dmg的磁盘映像。

use std::env;
use std::fs;
use std::process::Command;

fn setup_downloads(download_name: &str) {
    let downloads_path: String = {
        if cfg!(unix) {
            //these both yield options to unwrap
            let path = env::home_dir().unwrap();
            let mut downloads_path = path.to_str().unwrap().to_owned();
            downloads_path += "/Downloads/";
            downloads_path
        } else {
            "we currently only support Mac OS".to_string()
        }
    };

    let files_in_downloads =
        fs::read_dir(&downloads_path).expect("the read_dir that sets files_in_downloads broke");
    let mut file_path: String = "None".to_string();
    for file_name in files_in_downloads {
        let file_name: String = file_name
            .expect("the pre string result which sets file_name has broken")
            .file_name()
            .into_string()
            .expect("the post string result which sets file_name has broken")
            .to_owned();

        if file_name.contains(&download_name) {
            file_path = format!("'{}{}'", &downloads_path, &file_name);
        }
    }

    let len = file_path.len();

    if file_path[len - 4..len - 1] == "dmg".to_string() {
        let mount_command = ["hdiutil", "mount"];
        let output = Command::new(&mount_command[0])
            .arg(&mount_command[1])
            .arg(&file_path)
            .output()
            .expect("failed to execute mount cmd");

        if output.status.success() {
            println!(
                "command successful, returns: {}",
                String::from_utf8_lossy(&output.stderr).into_owned()
            );
        } else {
            println!(
                "command failed, returns: {}",
                String::from_utf8_lossy(&output.stderr).into_owned()
            );
        }
    }
}

fn main() {
    setup_downloads(&"StarUML".to_string());
}

macos process rust
1个回答
0
投票

Command拆分为变量并在指定参数后使用调试格式化程序将其打印出来:

let mut c = Command::new(&mount_command[0]);

c
    .arg(&mount_command[1])
    .arg(&file_path);

    println!("{:?}", c);

这输出

"hdiutil" "mount" "\'/Users/shep/Downloads/StarUML.dmg\'"

请注意,Command会自动为每个参数提供引用,但您已添加了自己的单引号集:

format!("'{}{}'", &downloads_path, &file_name);
//       ^    ^

删除这些单引号。

© www.soinside.com 2019 - 2024. All rights reserved.