簡體   English   中英

std::process::Command 無法在 macOS 上運行 hdiutil(掛載失敗 - 沒有此類文件或目錄),但該命令在終端中運行時運行良好

[英]std::process::Command cannot run hdiutil on macOS (mount failed - No such file or directory) but the command works fine when run in the terminal

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());
}

如果在下載中檢測到正確的文件時評估為真

來自 process::Command 的錯誤響應

將您的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);
//       ^    ^

刪除這些單引號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM