刚安装完python,准备pip安装第三方库的时候出现了一个错误:
UnicodeDecodeError: ‘ascii’ code can’t decode byte 0xef in position 7: ordinal not in range(128)
为什么会报错?
原因是pip安装python包会加载当前用户的用户目录,我的用户目录恰好是含有中文的,ascii不能进行编码。
![【python】pip安装报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 7: ordinal not in range(128) 【python】pip安装报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 7: ordinal not in range(128)](https://image.shishitao.com:8440/aHR0cHM6Ly9iYnNtYXguaWthZmFuLmNvbS9zdGF0aWMvTDNCeWIzaDVMMmgwZEhCekwybHRaeTFpYkc5bkxtTnpaRzR1Ym1WMEx6SXdNVGN3T1RBeU1UTXlOelUyTlRNNVAzZGhkR1Z5YldGeWF5OHlMM1JsZUhRdllVaFNNR05FYjNaTU1rcHpZakpqZFZrelRtdGlhVFYxV2xoUmRtUlVRWGhOZW1zd1QwUm5NVTlCUFQwdlptOXVkQzgxWVRaTU5Vd3lWQzltYjI1MGMybDZaUzgwTURBdlptbHNiQzlKTUVwQ1VXdEdRMDFCUFQwdlpHbHpjMjlzZG1Vdk56QXZaM0poZG1sMGVTOURaVzUwWlhJPS5qcGc%3D.jpg?w=700&webp=1)
解决办法1:
在python安装目录 Python27\Lib\site-packages 中新建一个文件sitecustomize.py
内容写:
内容写:
-
import sys
-
sys.setdefaultencoding(‘gb2312’)
python解析器会自动运行这个文件。sys.setdefaultencoding是python设置系统默认编码,大家可以在这里试试gbk也行(方法二用gbk尝试一下),配置好后,再在cmd窗口执行pip命令就可以了。
解决办法2:
修改python安装目录 Python27\Lib\目录下的mimetypes.py文件。
![【python】pip安装报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 7: ordinal not in range(128) 【python】pip安装报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 7: ordinal not in range(128)](https://image.shishitao.com:8440/aHR0cHM6Ly9iYnNtYXguaWthZmFuLmNvbS9zdGF0aWMvTDNCeWIzaDVMMmgwZEhCekwybHRaeTFpYkc5bkxtTnpaRzR1Ym1WMEx6SXdNVGN3T1RBeU1UTXpOakUzTXpFeFAzZGhkR1Z5YldGeWF5OHlMM1JsZUhRdllVaFNNR05FYjNaTU1rcHpZakpqZFZrelRtdGlhVFYxV2xoUmRtUlVRWGhOZW1zd1QwUm5NVTlCUFQwdlptOXVkQzgxWVRaTU5Vd3lWQzltYjI1MGMybDZaUzgwTURBdlptbHNiQzlKTUVwQ1VXdEdRMDFCUFQwdlpHbHpjMjlzZG1Vdk56QXZaM0poZG1sMGVTOURaVzUwWlhJPS5qcGc%3D.jpg?w=700&webp=1)
在import下添加如下几行:
-
if sys.getdefaultencoding() != 'gbk':
-
reload(sys)
-
sys.setdefaultencoding('gbk')
添加完成并保存,进入cmd窗口执行pip命令,结果是可行的。
![【python】pip安装报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 7: ordinal not in range(128) 【python】pip安装报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 7: ordinal not in range(128)](https://image.shishitao.com:8440/aHR0cHM6Ly9iYnNtYXguaWthZmFuLmNvbS9zdGF0aWMvTDNCeWIzaDVMMmgwZEhCekwybHRaeTFpYkc5bkxtTnpaRzR1Ym1WMEx6SXdNVGN3T1RBeU1UTXpPREk0TVRJMFAzZGhkR1Z5YldGeWF5OHlMM1JsZUhRdllVaFNNR05FYjNaTU1rcHpZakpqZFZrelRtdGlhVFYxV2xoUmRtUlVRWGhOZW1zd1QwUm5NVTlCUFQwdlptOXVkQzgxWVRaTU5Vd3lWQzltYjI1MGMybDZaUzgwTURBdlptbHNiQzlKTUVwQ1VXdEdRMDFCUFQwdlpHbHpjMjlzZG1Vdk56QXZaM0poZG1sMGVTOURaVzUwWlhJPS5qcGc%3D.jpg?w=700&webp=1)