Python 在英文版 Windows 系统下显示中文报错该怎么解决?

代码:

'''

-- coding: utf-8 --

print('中文') '''

报错:

''' File "C:\Users\Cstome\AppData\Local\Programs\Python\Python35\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 85-90: character maps to <undefined> '''

local 切换成简体中文就好了,但除此之外还有其他方法吗?


Python 在英文版 Windows 系统下显示中文报错该怎么解决?

2 回复

在英文版Windows上Python显示中文报错,通常是编码问题。核心解决方案是确保文件编码和终端编码一致。

1. 脚本文件编码声明 在Python文件开头添加编码声明:

# -*- coding: utf-8 -*-

2. 设置控制台编码 在代码中显式设置标准输出编码:

import sys
import io

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

3. 完整示例

# -*- coding: utf-8 -*-
import sys
import io

# 设置控制台编码为UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# 测试中文字符输出
print("中文测试")

4. 替代方案 如果上述方法无效,可以尝试:

print("中文测试".encode('utf-8').decode('utf-8'))

关键点:确保你的Python文件保存为UTF-8编码,并在代码中正确处理编码转换。

总结:统一使用UTF-8编码即可解决大部分中文显示问题。


The character encoding is platform-dependent. Under Windows, if the stream is interactive (that is, if its isatty() method returns True), the console codepage is used, otherwise the ANSI code page. Under other platforms, the locale encoding is used (see locale.getpreferredencoding()).

Under all platforms though, you can override this value by setting the PYTHONIOENCODING environment variable before starting Python.

所以,试试启动 python 前 chcp 65001

回到顶部