以下是应引起注意的声明UnicodeEncodeError
例外:
print 'str+{}'.format(u'unicode:\u2019')
在 Python shell 中,异常会按预期引发:
>>> print 'str+{}'.format(u'unicode:\u2019')
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
print 'str+{}'.format(u'unicode:\u2019')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 8: ordinal not in range(128)
但是,如果我将该行放在我的开头settings.py
并从 Aptana Studio 启动 Django 服务器,不会引发任何错误并打印以下行:
str+unicode:’
但如果我执行manage.py runserver
从 shell 中,会引发异常:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 8: ordinal not in range(128)
是否有某种 Python 设置可以默默地抑制这些 unicode 错误?
当我直接从 Aptana Studio 启动 Django 测试服务器时,如何防止忽略 unicode 错误?
Using
- Python 2.7.3
- 阿普塔纳工作室3.3.2
如果您只是将字节串转换为 unicode,例如
print unicode(s)
或者像你的例子一样在字符串格式化操作中混合unicode和字节串,Python将依靠系统默认编码(即ascii
除非它已被更改),并且隐式地会尝试使用以下方法对字节串进行编码/解码:ascii
codec.
当前活动的系统默认编码可以显示为
import sys
sys.getdefaultencoding()
现在看来 Aptana Studio 实际上确实扰乱了你的解释器的默认编码:
From a Mikko Ohtamaa 的博客文章 http://opensourcehacker.com/2010/01/24/aptana-studio-eclipse-pydev-default-unicode-encoding/:
[...] 看起来罪魁祸首是 PyDev(Eclipse Python 插件)。这
干扰源代码是here http://github.com/aptana/Pydev/blob/master/plugins/org.python.pydev/PySrc/pydev_sitecustomize/sitecustomize.py。
看起来原因是为了与 Eclipse 控制台配合。然而
这样做是错误的。而不是设置控制台编码,
编码设置为整个Python运行时环境,搞乱了
正在进行开发的目标运行时。
这个问题有一个可能的解决方法。在日食运行...您可以选择的对话框设置控制台编码 on Common标签。那里
是一个可能的值 US-ASCII。我不确定 Python 2 是怎么想的
“US-ASCII”编码名称,因为默认为“ascii”.
因此,请确保将默认值重置为ascii
,你应该很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)