Python, Unicode, and the Windows console

前端 未结 13 2180
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 04:38

When I try to print a Unicode string in a Windows console, I get a UnicodeEncodeError: \'charmap\' codec can\'t encode character .... error. I assume this is b

13条回答
  •  Happy的楠姐
    2020-11-21 05:04

    Note: This answer is sort of outdated (from 2008). Please use the solution below with care!!


    Here is a page that details the problem and a solution (search the page for the text Wrapping sys.stdout into an instance):

    PrintFails - Python Wiki

    Here's a code excerpt from that page:

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

    There's some more information on that page, well worth a read.

提交回复
热议问题