为什么在Python 2.4中使用Unicode数据而不是在2.7中得到ASCII编码错误? [英] Why do I get a ASCII encoding error with Unicode data in Python 2.4 but not in 2.7?

查看:107
本文介绍了为什么在Python 2.4中使用Unicode数据而不是在2.7中得到ASCII编码错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,当在Python 2.7中运行时,产生正确的Unicode输出到标准输出。当在Python 2.4中运行时,我得到 UnicodeEncodeError:'ascii'编解码器不能对位置1-4中的字符进行编码:ordinal不在范围(128)中。现在的版本2.4和2.7之间有什么变化?

解决方案

虽然我没有找到任何提及的elswhere, Python 2.7自动将文本转换为终端编码,而不是像预期那样抛出错误。



Python 2.7:

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

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

Python 2.6 (另一个框)

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

> python -c'import sys; sys.stdout.write(u\\\Σ)'
追溯(最近的最后一次调用):
文件< string>,第1行,< module>
UnicodeEncodeError:'ascii'编解码器不能编码字符u'\\\Σ'在位置0:序号不在范围(128)
> python -c'import sys; sys.stdout.write(u\\\Σ.encode(utf8))'
Σ

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


I have a program that, when run in Python 2.7, produces proper Unicode output to the standard output. When run in Python 2.4, I get UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128). What changed between version 2.4 and 2.7 that this works now?

解决方案

Although I could not find any mention of it elswhere, it appears that Python 2.7 is automatically converting text to the terminal encoding, instead of throwing an error as expected.

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 (on another box)

> 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"))'
Σ

In any case, an .encode("utf8") on the data before output should avoid the issue.

这篇关于为什么在Python 2.4中使用Unicode数据而不是在2.7中得到ASCII编码错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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