为了账号安全,请及时绑定邮箱和手机立即绑定

Python,Unicode和Windows控制台

Python,Unicode和Windows控制台

喵喵时光机 2019-05-28 17:42:29
Python,Unicode和Windows控制台当我尝试在Windows控制台中打印Unicode字符串时,出现UnicodeEncodeError: 'charmap' codec can't encode character ....错误。我认为这是因为Windows控制台不接受仅Unicode字符。最好的方法是什么??在这种情况下,有什么方法可以让Python自动打印而不是失败?编辑: 我正在使用Python 2.5。
查看完整描述

4 回答

?
婷婷同学_

TA贡献1844条经验 获得超8个赞

注意:这个答案有点过时(从2008年开始)。请小心使用以下解决方案!!


这是一个详细说明问题的页面和解决方案(在页面中搜索将sys.stdout包装到实例中的文本):

PrintFails - Python Wiki

这是该页面的代码摘录:

$ 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
  Б
  Б

有关该页面的更多信息,非常值得一读。


查看完整回答
反对 回复 2019-05-28
?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

尽管有其他看似合理的答案建议将代码页更改为65001,但这不起作用。(此外,使用更改默认的编码sys.setdefaultencoding不是一个好主意。)

有关详细信息和可行的代码,请参阅此问题


查看完整回答
反对 回复 2019-05-28
?
梵蒂冈之花

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控制台可打印的表示形式进行转换。


查看完整回答
反对 回复 2019-05-28
  • 4 回答
  • 0 关注
  • 842 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信