【问题标题】:python "print" doesn't work after sys.setdefaultencoding('utf-8') [duplicate]python“打印”在sys.setdefaultencoding('utf-8')之后不起作用[重复]
【发布时间】:2012-11-18 07:30:25
【问题描述】:

可能重复:
How to display utf-8 in windows console

python“打印”语句不起作用。

为了避免这个错误,

'ascii' 编解码器无法解码位置 0 中的字节 0xec:序数不在范围内(128)

我在下面的代码中添加了一些语句

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

在代码之前,“打印”效果很好。但是,在代码之后,“打印”不起作用。

print "A"

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

print "B"

这里,我的电脑上只打印了“A”,Python2.7.3 (64bit) for Windows。 Python2.7空闲

我需要帮助

【问题讨论】:

  • sys.setdefaultencoding 会在 sys 导入后从 sys 中删除。这是有据可查的,并且是有原因的。你不能这样使用sys.defaultencoding。请参阅链接的问题。
  • 其实我是用Aptana Studio 3而不是IDLE解决了这个问题。这可能是因为默认编码设置彼此不同。

标签: python printing


【解决方案1】:

sys.setdefaultencoding 因某种原因被site 删除,您不应使用reload(sys) 来恢复它。相反,我的解决方案是什么都不做,Python 会根据 ENV LANG 变量或 Windows chcp 编码自动检测编码。

$ python
Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import os
>>> sys.stdout.encoding
'UTF-8'
>>> os.environ["LANG"]
'pl_PL.UTF-8'
>>> print u"\xabtest\xbb"
«test»
>>>

但是当编码没有您想要的字符时,这可能会导致问题。您应该尝试优雅地降级 - 显示您想要的字符的机会接近 0(因此您应该尝试使用纯 ASCII 版本,或使用 Unidecode 来显示可用的输出(或干脆失败))。您可以尝试捕获异常并打印基本版本的字符串。

$ LANG=C python
Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import os
>>> sys.stdout.encoding
'ANSI_X3.4-1968'
>>> os.environ["LANG"]
'C'
>>> print u"\xabtest\xbb"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xab' in position 0: ordinal not in range(128)
>>>

但是有一个叫做 Windows 的问题在 Unicode 支持方面存在问题。虽然从技术上讲 chcp 65001 应该可以工作,但除非您使用 Python 3.3,否则它实际上不起作用。 Python 使用可移植的stdio.h,但cmd.exe 需要特定于Windows 的调用,例如WriteConsoleW()。只有 8 位编码才能可靠地工作(例如 CP437),真的。

解决方法是使用其他正确支持 Unicode 的终端,例如 Cygwin 的控制台或 Python 附带的 IDLE。

【讨论】:

    猜你喜欢
    • 2019-01-30
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多