我正在编写一个Python(Python 3.3)程序,使用POST方法将一些数据发送到网页.主要用于调试过程我得到页面结果并使用print()函数在屏幕上显示它.
代码是这样的:
conn.request("POST", resource, params, headers)
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data.decode('utf-8'));
Run Code Online (Sandbox Code Playgroud)
该HTTPResponse .read()方法返回一个bytes编码页面的元素(这是一个结构良好的UTF-8文档)在我停止使用Windows的IDLE GUI并使用Windows控制台之前,这似乎没问题.返回的页面有一个U + 2014字符(em-dash),打印功能可以在Windows GUI中很好地转换(我假定代码页1252),但不在Windows控制台中(代码页850).鉴于strict默认行为,我收到以下错误:
UnicodeEncodeError: 'charmap' codec can't encode character '\u2014' in position 10248: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
我可以使用这个非常难看的代码修复它:
print(data.decode('utf-8').encode('cp850','replace').decode('cp850'))
Run Code Online (Sandbox Code Playgroud)
现在用一个替换有问题的字符" - " ?.不是理想的情况(连字符应该是一个更好的替代品),但足够我的目的.
我的解决方案中有几件我不喜欢的东西.
问题不在于emdash(我可以想到解决这个问题的几种方法),但我需要编写健壮的代码.我正在向页面提供来自数据库的数据,并且数据可以返回.我可以预见到许多其他相互矛盾的情况:'Á'U+ 00c1(在我的数据库中可能)可以转换为CP-850(西欧语言的DOS/Windows控制台编码)但不能转换为CP-437(美国的编码)英语,在许多Windows instalations中是默认的).
那么,问题是:
有没有更好的解决方案使我的代码与输出接口编码无关?
这是代码:
>>> z = u'\u2022'.decode('utf-8', 'ignore')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'latin-1' codec can't encode character u'\u2022' in position 0: ordinal not in range(256)
Run Code Online (Sandbox Code Playgroud)
为什么在使用.decode时会引发UnicodeEncodeError?
当我使用'ignore'时,为什么会出现错误?