为啥我直接在shell下输入下面命令报错?
1 i4oolish@i4 /cygdrive/u/trunk/python 2 $ python 3 Python 2.7.3 (default, Dec 18 2012, 13:50:09) 4 [GCC 4.5.3] on cygwin 5 Type "help", "copyright", "credits" or "license" for more information. 6 >>> import sys 7 >>> sys.setdefaultencoding('iso-8859-1') 8 Traceback (most recent call last): 9 File "<stdin>", line 1, in <module> 10 AttributeError: 'module' object has no attribute 'setdefaultencoding' 11 >>>
上面第7行报错。而下面这样就可以
在python2.7的目录
i4oolish@i4 /usr/lib/python2.7/site-packages
中新建文件:sitecustomize.py,内容为:
1 import sys 2 sys.setdefaultencoding('iso-8859-1')
然后在shell下执行下面命令就是对的:
1 i4oolish@i4 /usr/lib/python2.7/site-packages 2 $ vi sitecustomize.py 3 4 i4oolish@i4 /usr/lib/python2.7/site-packages 5 $ cat sitecustomize.py 6 7 import sys 8 sys.setdefaultencoding('iso-8859-1') 9 10 i4oolish@i4 /usr/lib/python2.7/site-packages 11 $ python 12 Python 2.7.3 (default, Dec 18 2012, 13:50:09) 13 [GCC 4.5.3] on cygwin 14 Type "help", "copyright", "credits" or "license" for more information. 15 >>> import sys 16 >>> sys.getdefaultencoding() 17 'iso-8859-1' 18 >>>
这是为啥?
为了防止重新设置默认编码影响原本依赖ASCII编码的程序,Python编译器在启动时特意清除了sys模块的setdefaultencoding方法。如果需要调用,也可以reload(sys),然后就可以看到sys.setdefaultencoding方法了,不过设置之后就是后果自负了:-D