【问题标题】:Why do I get a ASCII encoding error with Unicode data in Python 2.4 but not in 2.7?为什么我在 Python 2.4 中收到 Unicode 数据的 ASCII 编码错误,但在 2.7 中却没有?
【发布时间】:2011-08-24 21:17:14
【问题描述】:

我有一个程序,当在 Python 2.7 中运行时,它会为标准输出生成正确的 Unicode 输出。在 Python 2.4 中运行时,我得到UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128)。 2.4 版和 2.7 版之间有什么变化现在可以使用?

【问题讨论】:

  • 我们不是通灵者。显示代码。
  • @Karl Knechtel:它只是来自如下声明:sys.stdout.write(unicode(data))sys.stdout.write(data)。问题是,这意味着问题来自其他地方......我不知道在哪里(应用程序相对较大)。
  • 试试import sys; print sys.getdefaultencoding()看看两者默认的unicode-to-string编码是否不同。
  • @Russell Borogove:好的,有趣,让我看看……两者都返回“asciii”!多么令人费解!
  • 关于故障点的数据(其来源、价值)您能告诉我们更多信息吗?

标签: python exception unicode encoding


【解决方案1】:

虽然我在其他地方找不到任何提及,但似乎 Python 2.7 会自动将文本转换为终端编码,而不是按预期抛出错误。

Python 2.7:

> echo $LANG
en_US.UTF-8
> python -c 'import sys; print sys.getdefaultencoding()'
ascii

> python -c 'import sys; sys.stdout.write(u"\u03A3")'
Σ
> python -c 'import sys; sys.stdout.write(u"\u03A3".encode("utf8"))'
Σ

Python 2.6(在另一个盒子上)

> echo $LANG
en_US.UTF-8
> python -c 'import sys; print sys.getdefaultencoding()'
ascii

> python -c 'import sys;  sys.stdout.write(u"\u03A3")'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec cant encode character u'\u03a3' in position 0: ordinal not in range(128)
> python -c 'import sys;  sys.stdout.write(u"\u03A3".encode("utf8"))'
Σ

在任何情况下,输出前的数据上的 .encode("utf8") 应该可以避免这个问题。

【讨论】:

  • Why.encode("utf-8") don't.encode("utf-8") you.encode("utf-8") just.encode("utf-8") set.encode("utf-8") the.encode("utf-8") stream.encode("utf-8") encoding.encode("utf-8") for.encode("utf-8") stdout.encode("utf-8") to.encode("utf-8") be.encode("utf-8") UTF-8.encode("utf-8") all.encode("utf-8 ") the.encode("utf-8") time?.encode("utf-8") that.encode("utf-8") saves.encode("utf-8") the.encode("utf- 8") 荒谬的.encode("utf-8") 和.encode("utf-8") 海量.encode("utf-8") annoyance.encode("utf-8") of.encode("utf- 8") this.encode("utf-8") specific.encode("utf-8") sort..encode("utf-8")
  • 不是他问题的答案,但如果有人感兴趣:import sys,codecs; sys.stdout = codecs.getwriter('utf8')(sys.stdout)
  • 谢谢。我自己将PYTHONIOENCODING 设置为utf8 运行,但大多数人似乎都接受Python 的海森编码策略。这让我太奇怪了。
猜你喜欢
  • 1970-01-01
  • 2023-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多