gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:36:14 26 4
gpt4 key购买 nike

hdiutils,当输入有效文件的正确路径时,返回错误 2,没有这样的文件或目录。当我用 "" 连接命令数组的索引、打印它们、复制它们并在终端中运行准确的字符串时,它工作正常。

这是经过编辑后仅包含相关位的函数。为了重现我的错误,您需要一个位于 ~/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());
}

if evaluates true when the correct file is detected in downloads

error response from 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);
// ^ ^

删除这些单引号。

关于macos - std::process::Command 无法在 macOS 上运行 hdiutil(安装失败 - 没有这样的文件或目录)但在终端中运行时该命令工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52347313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com