Python error: AttributeError: 'module' object has no attribute 'setdefaultencoding' problem solution

  • 2020-04-02 13:57:46
  • OfStack

Python's character set handling is a pain, currently using utf-8 in the majority, and then the default character set is ASCII, so we need to change to utf-8
View the current system character set


import sys
print sys.getdefaultencoding()

Perform:

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

Modified to utf-8

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

Perform:

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

Later, after looking up relevant information, I found that the earlier version can directly sys. Setdefaultencoding ('utf-8'), and the new version needs to be reloaded first

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

perform

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

 


Related articles: