
为了满足客户的需求,需要在前端中可以执行任意的cmd命令,然后在rust端执行,之前已经写过这个逻辑,但是今天发现出现了两个问题:1.cmd执行时间长的话,程序就会卡死,2.执行命令中包含中文的话,就会执行失败,今天就来讲一个该怎么解决这个两个问题
1.时间长程序卡死
要解决这个问题,就需要让cmd命令进行异步操作,改善后的程序如下,传递一个cmd命令字符串就可以了
rust
#[tauri::command]
pub async fn run_command(command: String) -> Result<String, String> {
let output = if cfg!(target_os = "windows") {
tokio::process::Command::new("cmd")
.args(&["/C", &command])
.output()
.await
.map_err(|e| e.to_string())?
} else {
tokio::process::Command::new("sh")
.arg("-c")
.arg(&command)
.output()
.await
.map_err(|e| e.to_string())?
};
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).to_string())
} else {
Err(String::from_utf8_lossy(&output.stderr).to_string())
}
}
2.中文报错问题
解决中文报错问题,可以使用双引号将中文包括起来,因为手动在cmd中操作,你会发现中文也是被双引号包括的,所以就模拟这个操作即可

如果是exe的路径中有中文呢?这里是没有双引号的

所以程序里也没问题:

可以执行成功,并会得到结果
