当我尝试在 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/