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());
}
答案 0 :(得分: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);
// ^ ^
删除这些单引号。