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

yipeiwu_com6年前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

 

相关文章

Python中asyncore异步模块的用法及实现httpclient的实例

基础 这个模块是socket的异步实现,让我们先来熟悉一下模块中的一些类和方法: 1.asyncore.loop 输入一个轮询循环直到通过计数或打开的通道已关闭。 2.asyncore....

200行python代码实现2048游戏

Python实战系列用于记录实战项目中的思路,代码实现,出现的问题与解决方案以及可行的改进方向 本文为第2篇–200行Python代码实现2048 一、分析与函数设计 1.1 游戏玩法...

Python实现压缩文件夹与解压缩zip文件的方法

本文实例讲述了Python实现压缩文件夹与解压缩zip文件的方法。分享给大家供大家参考,具体如下: 直接上代码 #coding=utf-8 #甄码农python代码 #使用zipfi...

python利用高阶函数实现剪枝函数

本文为大家分享了python利用高阶函数实现剪枝函数的具体代码,供大家参考,具体内容如下 案例:        某些时候,我们...

flask框架配置mysql数据库操作详解

flask框架配置mysql数据库操作详解

本文实例讲述了flask框架配置mysql数据库操作。分享给大家供大家参考,具体如下: 该篇博客配置环境为:python版本3.5,flask2.0,python3中已经不再支持MySQ...