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

yipeiwu_com5年前Python基础

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 <module>
    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

 

相关文章

win7安装python生成随机数代码分享

复制代码 代码如下:import random def genrand(small, big) :    return small + (big-small...

Python中struct模块对字节流/二进制流的操作教程

Python中struct模块对字节流/二进制流的操作教程

前言 最近使用Python解析IDX文件格式的MNIST数据集,需要对二进制文件进行读取操作,其中我使用的是struct模块。查了网上挺多教程都写的挺好的,不过对新手不是很友好,所以我重...

使用Python为中秋节绘制一块美味的月饼

使用Python为中秋节绘制一块美味的月饼

对于在外的游子,每逢佳节倍思亲。而对于996ICU的苦逼程序猿们,最期待的莫过于各种节假日能把自己丢在床上好好休息一下了。这几天各公司都陆续开始发中秋礼品了。朋友圈各种秀高颜值的月饼,所...

Python实现多线程的两种方式分析

本文实例讲述了Python实现多线程的两种方式。分享给大家供大家参考,具体如下: 目前python 提供了几种多线程实现方式 thread,threading,multithreadin...

Python控制Firefox方法总结

Python控制Firefox方法总结

有时候为了自动化测试网页,我们往往希望能够使用一些脚本语言控制浏览器. 通过脚本模拟一些浏览器动作,然后测试得到的结果.这里, 我们讲解一下如何使用Python语言控制Firefox浏览...