修改python默认的编码方式

今天碰到了 python 编码问题, 报错信息如下
Traceback (most recent call last):
  File "ntpath.pyc", line 108, in join
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa1 in position 36: ordinal not in range(128)

显然是当前的编码为ascii, 无法解析0xa1(十进制为161, 超过上限128). 进入python console后, 发现默认编码确实是 ascii, 验证过程为:

>>>import sys
>>>sys.getdefaultencoding()
#输出为ascii.

#在使用 sys.setdefaultencoding('utf8'), 报错!
>>>sys.setdefaultencoding('utf8')
AttributeError: 'module' object has no attribute 'setdefaultencoding'

google 到一个 limodou 回复的帖子, http://www.linuxforum.net/forum/showflat.php?Cat=&Board=python&Number=580942&page=15&view=collapsed&sb=5&o=

limodou讲到, sys.setdefaultencoding 方法在python导入 site.py 后就删除了, 不能再被调用了.  在确定sys已经导入的情况下, 可以reload sys这个模块, 之后, 再 sys.setdefaultencoding('utf8')
>>>reload(sys)
>>>sys.setdefaultencoding('utf8')

确实有效, 根据 limodou 讲解,  site.py 是 python 解释器启动后, 默认加载的一个脚本. 如果使用 python -S 启动的话, 将不会自动加载 site.py.

上面写的挺啰嗦的.

==================================
如何永久地将默认编码设置为utf-8呢?  有2种方法:
==================================
第一个方法<不推荐>: 编辑site.py, 修改setencoding()函数, 强制设置为 utf-8
第二个方法<推荐>: 增加一个名为 sitecustomize.py, 推荐存放的路径为 site-packages 目录下
sitecustomize.py 是在 site.py 被import 执行的, 因为 sys.setdefaultencoding() 是在 site.py 的结尾处被删除的, 所以, 可以在 sitecustomize.py 使用 sys.setdefaultencoding().
#file name:  sitecustomize.py
import sys  
sys.setdefaultencoding('utf-8')   

既然 sitecustomize.py 能被自动加载,  所以除了设置编码外, 也可以设置一些其他的东西. 

posted @ 2012-01-19 08:20  harrychinese  阅读(24916)  评论(0编辑  收藏  举报