Codex 中文乱码问题解决方案(Windows)

适用于 Codex / Copilot / AI 编码工具,Java / TypeScript / Python 项目


问题说明

在 Windows 11 环境下使用 AI 编码工具时,生成的代码中文经常变成乱码(如 æˆ'爱中文???),导致编译失败。

根本原因: AI 工具输出 UTF-8,但 Windows 终端默认使用 GBK 编码,编码冲突导致乱码。

Codex(UTF-8)→ Windows 终端(GBK)→ 文件写入(错误编码)→ IDE 读取(UTF-8)→ 乱码

解决核心原则:全链路统一为 UTF-8(无 BOM)


步骤 1:安装 Windows Terminal

如果你用的是老式的"命令提示符(cmd)"黑窗口,需要先装 Windows Terminal。

打开 cmd,运行:

winget install --id Microsoft.WindowsTerminal

如果 winget 报错,去 Microsoft Store(微软商店) 搜索 “Windows Terminal” 安装。

装完后按 Win 键搜索 “Terminal” 打开。


步骤 2:安装 PowerShell 7

在终端中运行:

winget install --id Microsoft.Powershell

安装完成后输入 pwsh 启动,验证版本:

pwsh
$PSVersionTable

确认 PSEdition 显示为 Core 即安装成功。


步骤 3:配置 PowerShell 7 的 Profile

在 pwsh 中运行:

New-Item -Path $PROFILE -ItemType File -Force
notepad $PROFILE

在打开的记事本中粘贴以下内容,保存并关闭:

[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
$PSDefaultParameterValues['Set-Content:Encoding'] = 'utf8'
$PSDefaultParameterValues['Add-Content:Encoding'] = 'utf8'

重新打开 pwsh,输入以下命令验证:

[Console]::OutputEncoding

显示 UTF-8 即配置成功。


步骤 4:将 Windows Terminal 默认终端改为 pwsh

  1. 打开 Windows Terminal
  2. 点击标签页旁边的下拉箭头 (或按 Ctrl + ,
  3. 左侧选择 “启动”
  4. “默认配置文件” 改为 PowerShell 7(pwsh)
  5. “保存”

⚠️ 不要使用 powershell.exe(旧版)或 cmd.exe


步骤 5:配置 IDE 编码

VSCode

Ctrl + , 打开设置:

  • Files: Encoding → 设为 utf8
  • Files: Auto Guess Encoding关闭

或直接在 settings.json 中添加:

{
  "files.encoding": "utf8",
  "files.autoGuessEncoding": false
}
IntelliJ IDEA

进入 Settings → Editor → File Encodings

  • Global Encoding → UTF-8
  • Project Encoding → UTF-8

步骤 6:项目级编码配置

在项目根目录创建两个文件:

.editorconfig
root = true

[*]
charset = utf-8
end_of_line = lf
.gitattributes
* text=auto eol=lf

*.java text working-tree-encoding=UTF-8
*.ts text working-tree-encoding=UTF-8
*.js text working-tree-encoding=UTF-8

步骤 7:给 Codex 添加 Prompt 约束

在与 Codex 对话时,提前加上以下约束:

生成代码必须遵守:
1. 所有文件编码 UTF-8(无 BOM)
2. 禁止 UTF-16 / GBK
3. 中文直接输出,不允许 \uXXXX
4. 文件写入必须使用 UTF-8

步骤 8:注意写文件的方式

不要用这些方式写文件(会产生 UTF-16):

echo "中文" > file.txt
Out-File file.txt

使用这种方式:

Set-Content file.txt -Encoding utf8

步骤 9(进阶):WSL / Bash 环境

如果 Codex 调用 bash 时出现乱码,设置环境变量:

$env:WSL_UTF8="1"

验证是否配置成功

运行以下命令测试:

Set-Content test.txt "你好世界" -Encoding utf8

用记事本或 VSCode 打开 test.txt,中文正常显示即配置成功。


优先级总结

优先级 操作 重要程度
1 安装 Windows Terminal ⭐⭐⭐ 必须
2 安装 PowerShell 7 ⭐⭐⭐ 必须
3 配置 UTF-8 Profile ⭐⭐⭐ 必须
4 改默认终端为 pwsh ⭐⭐⭐ 必须
5 IDE 设置 UTF-8 ⭐⭐⭐ 必须
6 添加 .editorconfig ⭐⭐ 推荐
7 Codex Prompt 约束 ⭐⭐ 推荐
8 WSL_UTF8 配置 ⭐ 进阶

完成以上配置后,可以解决 90% 以上的 Codex 中文乱码问题。

更多推荐