Python、Unicode 和 Windows 控制台 [英] Python, Unicode, and the Windows console

查看:38
本文介绍了Python、Unicode 和 Windows 控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I try to print a Unicode string in a Windows console, I get an error .

UnicodeEncodeError: 'charmap' 编解码器无法编码字符 ....

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

I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a ? instead of failing in this situation?

我使用的是 Python 2.5.

I'm using Python 2.5.

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

Note: @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!

@JFSebastian 的回答 从今天(2016 年 1 月 6 日)起更具相关性.

@JFSebastian answer is more relevant as of today (6 Jan 2016).

推荐答案

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

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

这是一个详细说明问题和解决方案的页面(在页面中搜索文本Wrapping sys.stdout into an instance):

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

该页面上还有更多信息,值得一读.

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

这篇关于Python、Unicode 和 Windows 控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆