在rust中执行命令行输出中文乱码解决办法

如果你使用标准的依赖库执行命令中包含中文的话, 就会发现中文乱码,如果你的输出中没有中文,就可以正常输出,因为windows的命令行默认使用的是gbk编码。。。。。

rust 复制代码
#[tauri::command]
pub async fn run_command(command: String) -> Result<String, String> {
    #[cfg(target_os = "windows")]
    let output = {
        // 先设置控制台编码为UTF-8
        let _ = 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"

完整代码:

rust 复制代码
#[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-8
            let (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())
        }
    }
}
相关推荐
拾柒SHY8 分钟前
XSS-Labs靶场通关
前端·web安全·xss
前端婴幼儿13 分钟前
前端主题切换效果
前端
一 乐15 分钟前
水果销售|基于springboot + vue水果商城系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端
Qin_jiangshan19 分钟前
如何成为前端架构师
前端
dolt0241 分钟前
基于deepseek实现的ai问答小程序
前端·开源
一只小bit1 小时前
Qt 快速开始:安装配置并创建简单标签展示
开发语言·前端·c++·qt·cpp
加蓓努力我先飞1 小时前
a-第一部分-基础篇-前端面试题总结
前端
青莲8431 小时前
Android Jetpack - 3 LiveData
android·前端
Syron1 小时前
ScaleSlider 组件实现
javascript
xhxxx1 小时前
深入执行上下文:JavaScript 中 this 的底层绑定机制
javascript