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

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 程序和Web请求调用locale.getpreferredencoding(),则编码为“UTF-8”。

从几天开始,我在代码中更新了异常处理并记录了getpreferredencoding()。现在又发生了一次(到目前为止,我还不能强制或复制它),编码为“ANSI_X3.4-1968”!

我不知道在哪里设置此编码...。

这使我的问题朝着不同的方向发展。这个问题毫无用处。我的问题现在是:首选编码在哪里更改?但这不是这个问题的一部分。

非常感谢所有的人

最佳答案

您依赖于平台的默认编码。如果该默认编码不支持您要写入文件的Unicode字符,则会出现编码异常。

io.open() documentation:



对于您的特定情况,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/

10-13 02:58