一直以来认为解决 python 字符集编码, 不一定需要通过 sys.setdefaultencoding. 因为既然 python 实现过程中, 默认禁用了该操作, 说明是不推荐的.
通过不断的字符转换, 也 cover 了一些问题.
但今天在把 python 输出的中文重定向到文件作为日志输出时, 遇到了问题.
直接打屏没问题, 但重定向到文件就会有问题.
日志
- calculate for cc with result list offset 0 -> 255
- Traceback (most recent call last):
- File "hive_stats_sql_operation.py", line 325, in <module>
- print job_report(_result_file = result_file, _pre_job_key = pre_job_key)
- File "hive_stats_sql_operation.py", line 286, in job_report
- print dict_format(reduce(lambda x,y : x + y, local_result_list), ensure_ascii=False)
- UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-32: ordinal not in range(128)
问题复现与排查
- #!/bin/env python
- #coding:utf8
- import sys
- print sys.stdout.encoding
- #first
python code.py
- #UTF-8
- #second
- python code.py> debug ; cat debug
- # None
问题的解决
问题的原因也知道了, 那么解决方法也就很明了了, 就是让字符串正确的 decode 就 ok 了, 所以有如下几种方法:
在代码的开始调用 reload(sys);sys.setdefaultencoding('utf8') 通过这种方式, 我们制定了默认的 encode 字符集为 utf8 因此修正了以上错误
在 print u1 的地方改成 print u1.decode('utf8').encode('utf8') 由我们来指定调用的字符集防止其调用默认的 ascii
来源: http://www.bubuko.com/infodetail-3028359.html