Python,Unicode和Windows控制台当我尝试在Windows控制台中打印Unicode字符串时,出现UnicodeEncodeError: 'charmap' codec can't encode character ....错误。我认为这是因为Windows控制台不接受仅Unicode字符。最好的方法是什么??在这种情况下,有什么方法可以让Python自动打印而不是失败?编辑: 我正在使用Python 2.5。
4 回答
![?](http://img1.sycdn.imooc.com/533e4c0500010c7602000200-100-100.jpg)
婷婷同学_
TA贡献1844条经验 获得超8个赞
注意:这个答案有点过时(从2008年开始)。请小心使用以下解决方案!!
这是一个详细说明问题的页面和解决方案(在页面中搜索将sys.stdout包装到实例中的文本):
这是该页面的代码摘录:
$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' UTF-8 <type 'unicode'> 2 Б Б $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' | cat None <type 'unicode'> 2 Б Б
有关该页面的更多信息,非常值得一读。
![?](http://img1.sycdn.imooc.com/54584d1300016b9b02200220-100-100.jpg)
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
如果你对获得可靠的坏字符表示不感兴趣,可以使用类似的东西(使用python> = 2.6,包括3.x):
from __future__ import print_functionimport sysdef safeprint(s): try: print(s) except UnicodeEncodeError: if sys.version_info >= (3,): print(s.encode('utf8').decode(sys.stdout.encoding)) else: print(s.encode('utf8'))safeprint(u"\N{EM DASH}")
字符串中的错误字符将以Windows控制台可打印的表示形式进行转换。
添加回答
举报
0/150
提交
取消