问题描述

由于某些作业的需求,我不得不使用 python 2.7.x(甚至是跑人工智能,甚至还在用python2,真是吃不消了),用 conda 创建完 python 2.7.x 的环境后准备用 pip 安装软件包,然后就开始疯狂报错orz

报错内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
(ai1) PS D:\JetBrains\JetbrainProjects\PyCharmProjects\AI\lab1> pip install scipy==0.18.1
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting scipy==0.18.1
ERROR: Exception:
Traceback (most recent call last):
File "D:\Code_about\Anaconda3\envs\ai1\lib\site-packages\pip\_internal\cli\base_command.py", line 153, in _main
status = self.run(options, args)
File "D:\Code_about\Anaconda3\envs\ai1\lib\site-packages\pip\_internal\commands\install.py", line 382, in run
resolver.resolve(requirement_set)
File "D:\Code_about\Anaconda3\envs\ai1\lib\site-packages\pip\_internal\legacy_resolve.py", line 201, in resolve
self._resolve_one(requirement_set, req)
File "D:\Code_about\Anaconda3\envs\ai1\lib\site-packages\pip\_internal\legacy_resolve.py", line 365, in _resolve_one
abstract_dist = self._get_abstract_dist_for(req_to_install)
File "D:\Code_about\Anaconda3\envs\ai1\lib\site-packages\pip\_internal\legacy_resolve.py", line 313, in _get_abstract_dist_for
req, self.session, self.finder, self.require_hashes
File "D:\Code_about\Anaconda3\envs\ai1\lib\site-packages\pip\_internal\operations\prepare.py", line 194, in prepare_linked_requirement
progress_bar=self.progress_bar
File "D:\Code_about\Anaconda3\envs\ai1\lib\site-packages\pip\_internal\download.py", line 465, in unpack_url
progress_bar=progress_bar
File "D:\Code_about\Anaconda3\envs\ai1\lib\site-packages\pip\_internal\download.py", line 316, in unpack_http_url
progress_bar)
File "D:\Code_about\Anaconda3\envs\ai1\lib\site-packages\pip\_internal\download.py", line 549, in _download_http_url
file_path = os.path.join(temp_dir, filename)
File "D:\Code_about\Anaconda3\envs\ai1\lib\ntpath.py", line 85, in join
result_path = result_path + p_path
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd6 in position 7: ordinal not in range(128)

解决方案

前面的几行都是让你不要再用 python 2.7 了(废话,我也不想用啊),下面是报错信息,我们可以看到是发生在一个路径合并函数中,需要 ascii 字符,但是检测到了非 ascii 字符,这bug . . . . . . 挺邪门啊。

原因是 python2 默认编码是 ascii ,而 pip 把下载的临时文件存放在了用户临时文件中,如果用户名是中文自然就有非 ascii 字符,因此会报错了。

解决方法是找到 python2.7 目录下的 Lib 文件夹中的 ntpath.py 文件(如果是使用 anaconda 虚拟环境的话,这个文件的路径是: \envs\{{env_name}}\Lib\ntpath.py),打开,找到 def join(path, *paths) 方法,在下面添加两行代码:

1
2
reload(sys)  
sys.setdefaultencoding('gbk')

这样就能解决非 ascii 问题了。

重新使用 pip 安装包,下载成功!