如果你使用標準的依賴庫執行命令中包含中文的話, 就會發現中文亂碼,如果你的輸出中沒有中文,就可以正常輸出,因為windows的命令行默認使用的是gbk編碼。。。。。
#[tauri::command]
pub async fn run_command(command: String) -> Result<String, String> {#[cfg(target_os = "windows")]let output = {// 先設置控制臺編碼為UTF-8let _ = tokio::process::Command::new("powershell").arg("-Command").arg("chcp 65001 | Out-Null").creation_flags(0x08000000).status().await;tokio::process::Command::new("powershell").arg("-Command").arg(&command).creation_flags(0x08000000).output().await.map_err(|e| e.to_string())?};#[cfg(not(target_os = "windows"))]let output = tokio::process::Command::new("sh").arg("-c").arg(&command).output().await.map_err(|e| e.to_string())?;if output.status.success() {print!("Command output: {}",String::from_utf8_lossy(&output.stdout));Ok(String::from_utf8_lossy(&output.stdout).to_string())} else {Err(String::from_utf8_lossy(&output.stderr).to_string())}
}
解決辦法
使用標準的編碼依賴庫encoding_rs = "0.8"
完整代碼:
#[tauri::command]
pub async fn run_command(command: String) -> Result<String, String> {#[cfg(target_os = "windows")]let output = tokio::process::Command::new("powershell").arg("-Command").arg(&command).creation_flags(0x08000000).output().await.map_err(|e| e.to_string())?;#[cfg(not(target_os = "windows"))]let output = tokio::process::Command::new("sh").arg("-c").arg(&command).output().await.map_err(|e| e.to_string())?;if output.status.success() {#[cfg(target_os = "windows")]{// 在Windows上嘗試從GBK轉換為UTF-8let (decoded, _, _) = GBK.decode(&output.stdout);Ok(decoded.into_owned())}#[cfg(not(target_os = "windows"))]{Ok(String::from_utf8_lossy(&output.stdout).to_string())}} else {#[cfg(target_os = "windows")]{let (decoded, _, _) = GBK.decode(&output.stderr);Err(decoded.into_owned())}#[cfg(not(target_os = "windows"))]{Err(String::from_utf8_lossy(&output.stderr).to_string())}}
}