Python、Unicode 和 Windows 控制台

标签 python unicode

当我尝试在 Windows 控制台中打印 Unicode 字符串时,出现错误。

UnicodeEncodeError: 'charmap' codec can't encode character ....

我认为这是因为 Windows 控制台不接受纯 Unicode 字符。解决这个问题的最佳方法是什么? 有什么方法可以让 Python 自动打印 而不是在这种情况下失败?

编辑:我使用的是 Python 2.5。


注意: @LasseV.Karlsen 带有复选标记的答案有点过时(从 2008 年开始)。请谨慎使用下面的解决方案/答案/建议!!

@JFSebastian answer截至今天(2016 年 1 月 6 日),相关性更高。

最佳答案

更新: Python 3.6实现 PEP 528: Change Windows console encoding to UTF-8 : Windows 上的默认控制台现在将接受所有 Unicode 字符。 在内部,它使用与 the win-unicode-console package mentioned below 相同的 Unicode API . print(unicode_string) 现在应该可以工作了。


I get a UnicodeEncodeError: 'charmap' codec can't encode character... error.

该错误意味着您尝试打印的 Unicode 字符无法使用当前 (chcp) 控制台字符编码来表示。代码页通常是 8 位编码,例如 cp437,它只能表示 ~1M Unicode 字符中的 ~0x100 个字符:

>>> u"\N{EURO SIGN}".encode('cp437')
Traceback (most recent call last):
...
UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in position 0:
character maps to 

I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this?

Windows console does accept Unicode characters and it can even display them (BMP only) if the corresponding font is configured. WriteConsoleW() API should be used as suggested in @Daira Hopwood's answer. It can be called transparently i.e., you don't need to and should not modify your scripts if you use win-unicode-console package:

T:\> py -m pip install win-unicode-console
T:\> py -m run your_script.py

What's the deal with Python 3.4, Unicode, different languages and Windows?

Is there any way I can make Python automatically print a ? instead of failing in this situation?

如果在您的情况下用 ? 替换所有不可编码的字符就足够了,那么您可以设置 PYTHONIOENCODING envvar :

T:\> set PYTHONIOENCODING=:replace
T:\> python3 -c "print(u'[\N{EURO SIGN}]')"
[?]

在 Python 3.6+ 中,由 PYTHONIOENCODING envvar 指定的编码对于交互式控制台缓冲区将被忽略,除非 PYTHONLEGACYWINDOWSIOENCODING envvar 设置为非空字符串。

关于Python、Unicode 和 Windows 控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5419/

相关文章:

unicode - 如何从 Unicode 网站获取完整的 Unicode 表情符号列表

javascript - 文件上传后是否可以留在页面上并收到“确定”消息?

python - 对于大型数组的手动元素操作,numpy 的更快替代方案?

Python在网格上绘制填充的 "Circle"

python - Argparse,处理可重复的项目集

string - Swift 字符串比较使用哪种规范化?

MySQL 处理 utf8mb4_unicode_ci 的 unicode 文本

unicode - 如何在 Tkinter 中打印非 BMP Unicode 字符(例如 𝄫)

python - 如何与 Pyramid 中的所有模板共享选定数量的数据?

python - AppVeyor 中的 UTF-8,Python 3.6