Skip to main content
 首页 » 编程设计

python之从 Aptana Studio PyDev 运行时取消抑制 UnicodeEncodeError 异常

2024年10月25日8pander-it

下面是一个应该引发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:’ 

但是,如果我从 shell 中执行 manage.py runserver,则会引发异常:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 8: ordinal not in range(128) 

是否有某种 Python 设置可以默默地抑制这些 un​​icode 错误?

如何防止直接从Aptana Studio启动Django测试服务器时忽略unicode错误?

使用

  • python 2.7.3
  • Aptana Studio 3.3.2

请您参考如下方法:

如果你简单地将字节串转换为 unicode,比如

print unicode(s) 

或者像你的例子一样在字符串格式化操作中混合 unicode 和 bytestrings,Python 将回退到系统默认编码(即 ascii 除非它已被更改),并隐式地尝试编码 unicode/使用 ascii 编解码器解码字节串。

可以显示当前事件的系统默认编码

import sys 
sys.getdefaultencoding() 

现在看来 Aptana Studio 实际上确实扰乱了解释器的默认编码:

来自blog post by Mikko Ohtamaa :

[...] Looks like the culprint was PyDev (Eclipse Python plug-in). The interfering source code is here. Looks like the reason was to co-operate with Eclipse console. However it has been done incorrectly. Instead of setting the console encoding, the encoding is set to whole Python run-time environment, messing up the target run-time where the development is being done.

There is a possible fix for this problem. In Eclipse Run… dialog settings you can choose Console Encoding on Common tab. There is a possible value US-ASCII. I am not sure what Python 2 thinks “US-ASCII” encoding name, since the default is “ascii”.

因此,请确保将默认值重置为 ascii,这样就可以了。