Python pip install 出现UnicodeDecodeError: 'ascii' codec can't decode byte 0xb1 in position 34:错误的解决方法

来源:互联网 发布:巨杉数据库 创始人 编辑:程序博客网 时间:2024/05/22 15:09

今天在用pip安装pandas的时候出现错误:

UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xb1 in position 34:

从错误类型上看,UnicodeDecodeError是编码错误。
其实在默认情况下,python的编码都是按ascii来编码的,当碰到Unicode编码时,就会报错。这时候就需要声明用utf-8来编码。
通常在写程序时,声明utf8可以用一下两种方式:

# coding=utf-8#如果你想用其他编码可以按照以下格式修改:# coding=<encoding name> 
#!/usr/bin/python# -*- coding: utf-8 -*-# -*- coding: <encoding name> -*-  

下面这个网址时python官方文档,对编码解释很详细:
https://www.python.org/dev/peps/pep-0263/

回归主题。
如果安装时遇到这种问题该怎么办呢?
这时候我们需要修改/etc/python2.7下的一个sitecustomize.py文件。这个文件用于定义当前环境的编码。

https://www.python.org/dev/peps/pep-0100/
这是python的官方文档,里面有一段提到:

Note that the default site.py startup module contains disabled optional code which can set the according to the encoding defined by the current locale. The locale module is used to extract the encoding from the locale default settings defined by the OS environment (see locale.py). If the encoding cannot be determined, is unkown or unsupported, the code defaults to setting the to ‘ascii’. To enable this code, edit the site.py file or place the appropriate code into the sitecustomize.py module of your Python installation.

我们只需要在sitecustomize.py中加入:

# -*- coding: utf-8 -*-import sysreload(sys)sys.setdefaultencoding('utf8')

即可

接着可以在python交互模式中验证是否改变默认的编码方式

>>> import sys>>> sys.getdefaultencoding()'utf8'

然后就可以重新安装python第三方模块了。

0 0
原创粉丝点击