Windows Terminal中PyPy3无法正确显示非ASCII Unicode字符的解决咨询
问题描述
在Windows 11的Windows Terminal中运行PyPy3时,非ASCII Unicode字符无法正确显示。比如执行以下代码:
b'\xce\x9e\xce\xad\xce\xbd\xce\xb7 \xce\x93\xce\xae\xce\xb9\xce\xbd\xce\xbf\xcf\x82'.decode('utf8')
预期输出应该是'Ξένη Γήινος',但实际得到乱码:
In [1]: b'\xce\x9e\xce\xad\xce\xbd\xce\xb7 \xce\x93\xce\xae\xce\xb9\xce\xbd\xce\xbf\xcf\x82'.decode('utf8') Out[1]: '╬×╬¡╬¢╬À ╬ô╬«╬╣╬¢╬┐¤é'
这是PyPy的已知未修复问题,根源在于Windows默认的cp1252代码页和PyPy的编码处理不匹配。试过设置PYTHONIOENCODING环境变量、执行chcp 65001都没用,只有先在PowerShell里设置控制台输入输出编码为UTF-8,再启动PyPy才能正常显示。下面是直接在Windows Terminal中启动PyPy就解决问题的方法:
解决方法
方法1:修改Windows Terminal的PyPy启动配置
- 打开Windows Terminal,点击顶部下拉菜单的「设置」
- 在左侧列表找到PyPy的配置项(如果没有,先添加一个)
- 把「命令行」字段修改为:
把powershell -Command "$OutputEncoding = [Console]::OutputEncoding = [Console]::InputEncoding = [System.Text.UTF8Encoding]::new(); & 'C:\你的PyPy路径\pypy3.exe'"C:\你的PyPy路径\pypy3.exe替换成你实际的PyPy安装路径,比如C:\Program Files\PyPy3\pypy3.exe
方法2:创建批处理文件启动PyPy
- 在PyPy的安装目录下新建一个
start_pypy.bat文件,写入以下内容:@echo off powershell -Command "$OutputEncoding = [Console]::OutputEncoding = [Console]::InputEncoding = [System.Text.UTF8Encoding]::new(); & '%~dp0pypy3.exe'" - 保存后,直接在Windows Terminal里运行这个批处理,或者把它添加到Windows Terminal的启动项列表中,以后直接点击就能启动正常显示Unicode的PyPy
方法3:永久设置PowerShell编码(不推荐)
如果不想每次单独配置PyPy,可以修改PowerShell的全局配置,让它每次启动都自动设置UTF-8编码:
- 打开PowerShell,输入
notepad $PROFILE打开配置文件(如果提示文件不存在,先执行New-Item -Path $PROFILE -ItemType File创建) - 在文件里添加一行:
$OutputEncoding = [Console]::OutputEncoding = [Console]::InputEncoding = [System.Text.UTF8Encoding]::new() - 保存后重启PowerShell,之后在PowerShell里启动PyPy就能正常显示Unicode字符了
环境信息参考
PyPy win32 3.11.11 (0253c85bf5f8, 2025年2月26日, 10:43:25)
[PyPy 7.3.19 搭配 MSC v.1941 64位 (AMD64)]
os.device_encoding(0)='cp850'
os.device_encoding(1)='cp850'
sys.getdefaultencoding()='utf-8'
sys.getfilesystemencoding()='utf-8'
locale.getpreferredencoding()='utf-8'
locale.getencoding()='utf-8'
locale.getlocale()=('English_United States', '1252')
locale.getlocale()=('English_United States', '1252')
内容的提问来源于stack exchange,提问作者Ξένη Γήινος

