python - 如何重现 UnicodeEncodeError?

标签 python python-2.7 python-unicode

我在生产系统中遇到错误,但我无法在开发环境中重现该错误:

with io.open(file_name, 'wt') as fd:
    fd.write(data)

异常(exception):

  File "/home/.../foo.py", line 18, in foo
    fd.write(data)

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

我已经尝试将很多奇怪的字符放入变量 data 中。

但到目前为止,我无法重现 UnicodeEncodeError

data 中需要包含什么才能得到 UnicodeEncodeError

更新

python -c 'import locale; print locale.getpreferredencoding()'
UTF-8

更新2

如果我通过 shell 和网络请求调用 locale.getpreferredencoding(),编码是“UTF-8”。

我在我的代码中更新了我的异常处理并记录了 getpreferredencoding() 几天以来。现在又发生了(到现在我还不能强制或重现这个),编码是“ANSI_X3.4-1968”!

我不知道这个编码是在哪里设置的....

这使我的问题转向了不同的方向。留下这个问题没有用。我现在的问题是:首选编码在哪里更改?但这不是这个问题的一部分。

非常感谢所有的人

最佳答案

您依赖平台的默认编码;当默认编码不支持您写入文件的 Unicode 字符时,您会遇到编码异常。

来自io.open() documentation :

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any encoding supported by Python can be used.

对于您的具体情况,locale.getpreferredencoding() 返回的默认值是 ASCII,因此 ASCII 范围之外的任何 Unicode 字符都会导致此问题,U-0080 及以上。

请注意,语言环境取自您的环境;如果它是 ASCII,这通常意味着语言环境设置为 POSIX default locale, C .

明确指定编码:

with io.open(file_name, 'wt', encoding='utf8') as fd:
    fd.write(data)

我以 UTF-8 为例;您选择什么完全取决于您的用例和您尝试写出的数据。

关于python - 如何重现 UnicodeEncodeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41568129/

相关文章:

python - 在python中计算.wav文件的频谱图

python - 修改递归子集和 + Memoize 打印值

python - 同时应用于多行

python - 如何在 python 中合并或连接两个 midi 文件

python - 安装 Python 时出现问题

python - 如何让我的 Python 解析以下文本?

python - Django中邮箱验证的实现

python - 同时显示多个vtk渲染窗口

python - 将结果从 python 写入 csv 文件 [UnicodeEncodeError : 'charmap' codec can't encode character

python - API 调用 (json) 上的 UnicodeEncodeError