#!/usr/bin/env python
#encoding: utf-8
import sys #引用sys模块进来,并不是进行sys的第一次加载
reload(sys) #重新加载sys
sys.setdefaultencoding('utf8') ##调用setdefaultencoding函数
可以正确的执行,可是卡死在reload(sys)的位置。同样无法达到修改默认字符编码的目的。
最后会给出解决方法
#!/usr/bin/env python
#encoding: utf-8
import sys
sys.setdefaultencoding('utf8')
要在调用setdefaultencoding时必须要先reload一次sys模块,因为这里的import语句其实并不是sys的第一次导入语句,也就是说这里其实可能是第二、三次进行sys模块的import,这里只是一个对sys的引用,只能reload才能进行重新加载。
那么为什么要重新加载,而直接引用过来则不能调用该函数呢?因为setdefaultencoding函数在被系统调用后被删除了,所以通过import引用进来时其实已经没有了,所以必须reload一次sys模块,这样setdefaultencoding才会为可用,才能在代码里修改解释器当前的字符编码。
在python安装目录的Lib文件夹下,有一个叫site.py的文件,在里面可以找到main() –> setencoding()–>sys.setdefaultencoding(encoding),因为这个site.py每次启动python解释器时会自动加载,所以main函数每次都会被执行,setdefaultencoding函数一出来就已经被删除了。
解决方法:
/Lib/site.py
def setencoding():
"""Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this."""
#encoding = "ascii" # Default value set by _PyUnicode_Init()
encoding = "GBK" # 修改成你需要的字符集
if 0:
# Enable to support locale aware default string encodings.
import locale
loc = locale.getdefaultlocale()
if loc[1]:
encoding = loc[1]
if 0:
# Enable to switch off string to Unicode coercion and implicit
# Unicode to string conversion.
encoding = "undefined"
if encoding != "ascii":
# On Non-Unicode builds this will raise an AttributeError...
sys.setdefaultencoding(encoding) # Needs Python Unicode build !