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

标签 python django unicode python-unicode

以下是应引发 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和字节串(如您的示例),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,这样就可以了。

关于python - 从 Aptana Studio PyDev 运行时取消抑制 UnicodeEncodeError 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25250857/

相关文章:

Python 代码在 Eclipse 中出错,但在终端中运行良好

python - 如何找到列表中最长的列表?

python Django : pre-select dropdown of custom field

python - Imagekit - 删除原始图像后未删除缓存图像

unicode - 如何在 Windows 命令行上使用 Unicode 字符?

Python Unicode 转换

python - 在 python boto 中使用 cognito 获取 AWS 凭证

python - 通过仅跳过空白行来读取 excel 文件 (pd.read_excel())

django - 在 Django admin 中注册 SQL 表

javascript - 有一个更好的方法吗? (递归解析 HTML unicode 实体)