blueyi's notes

Follow Excellence,Success will chase you!

0%

python 2.7 UnicodeEncodError

python 2.7.13中采用print输出内容后,通过terminal的管道重定向到文件时出错:

1
UnicodeEncodeError: 'ascii' codec can't encode characters in position 19-20: ordinal not in range(128)

应该是编码的问题,然后就搜索发现python处理的代码文件的编码,系统默认编码都不一样,虽然可以通过对str进行decode(‘gbk’)的方式将中文正常输出,但重定向时,由于系统编码不一致,导致上述错误。可以通过设置系统编码来解决:

1
reload(sys).setdefaultencoding("utf8")

使用场景,通过requests获取中文网页,为了方便日常分析使用,会考虑将内容正常输出到标准输出,然后需要输出到文件时再进行重定向,而且还希望文件编码格式统一采用utf-8,代码如下:

1
2
3
# ...
reload(sys).setdefaultencoding("utf8")
print(re.search(regex, requests.get('http://example.com').content).group(0).decode('gbk'))

这样即可以正常输出中文到标准输出,也可以将其正常重定向到文件,而且不需要修改系统的默认文件编码

参考:
1.http://stackoverflow.com/questions/15530635/why-is-sys-getdefaultencoding-different-from-sys-stdout-encoding-and-how-does
2.http://stackoverflow.com/questions/11741574/how-to-print-utf-8-encoded-text-to-the-console-in-python-3

Welcome to my other publishing channels