>  기사  >  백엔드 개발  >  python错误:AttributeError: 'module' object has no attribute 'setdefaultencoding'问题的解决方法

python错误:AttributeError: 'module' object has no attribute 'setdefaultencoding'问题的解决方法

WBOY
WBOY원래의
2016-06-16 08:42:371993검색

Python的字符集处理实在蛋疼,目前使用UTF-8居多,然后默认使用的字符集是ascii,所以我们需要改成utf-8
查看目前系统字符集

复制代码 代码如下:

import sys
print sys.getdefaultencoding()

执行:
复制代码 代码如下:

[root@lee ~]# python a.py
ascii

修改成utf-8
复制代码 代码如下:

import sys
 
sys.setdefaultencoding('utf-8')
 
print sys.getdefaultencoding()

执行:
复制代码 代码如下:

[root@lee ~]# python a.py
Traceback (most recent call last):
  File "a.py", line 4, in
    sys.setdefaultencoding('utf-8')
AttributeError: 'module' object has no attribute 'setdefaultencoding'
提示:AttributeError: 'module' object has no attribute 'setdefaultencoding'?

后来经过查找相关资料,才发现早期版本可以直接sys.setdefaultencoding('utf-8'),新版本需要先reload一下
复制代码 代码如下:

import sys
 
reload(sys)
sys.setdefaultencoding('utf-8')
 
print sys.getdefaultencoding()

执行
复制代码 代码如下:

[root@lee ~]# python a.py
utf-8

 
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.