【Python学习】通过pip安装第三方库

这不是一个教程,只是笔者在学习Python过程中遇到问题+解决问题的记录和分享。

Python第三方库的安装是Python学习中笔者遇到的第一个坎儿。网上的教程只说“打开CMD输入pip install XXX”,就完事儿了,看得人一脸懵。

实际的操作步骤是这样的,我们默认在windows环境下,“win”+“r”打开运行程序,输入cmd,打开命令提示符。

此时直接输入pip install XXX 会报错,正确的做法是在此之前加上Python的安装路径+Scripts,以安装中文分词库jieba为例,在cmd中输入:

C:\Python37\Scripts\pip install jieba

*附cmd操作技巧:
输入 c: 后回车——跳转到C盘;
输入 cd\ 后回车——回到磁盘目录。

如果安装失败,有以下几种解决路径:

首先,检查cmd环境下Python可否正常运行。输入Python安装目录+python:

C:\Python37\python

如果自动显示python版本等信息,则Python路径运行没有问题:


> Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC
> v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or
> "license" for more information.

如果报错,此时需要“添加环境变量”。

具体操作路径为:“我的电脑”——“属性”——“高级系统设置”——“环境变量”,找到“Path”,输入“;”后添加Python安装路径+Scripts即可。

cmd环境下Python可以正常运行,仍然报错,通常是因为超时报错(“read time out”)。原因是Python的第三方库默认从海外下载,可能会比较慢,这个时候我们可以选择用国内的镜像源。

扫描二维码关注公众号,回复: 5576555 查看本文章

推荐使用豆瓣或清华的源:

http://pypi.douban.com/ 豆瓣
https://pypi.tuna.tsinghua.edu.cn/ 清华

使用方法:在 pip 后输入 “-i” 来指定源,如用豆瓣的源来安装jieba库:

C:\>Python37\Scripts\pip install jieba -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

注意指定源后面要加上“simple”,同时要输入“–trusted-host”+源地址,这个是为了防止没有匹配的版本报错(No matching distribution)

The repository located at pypi.douban.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with ‘–trusted-host pypi.douban.com’.

或者如系统提示所说,换用https的源,如清华的源:

C:\>Python37\Scripts\pip install jieba -i https://pypi.tuna.tsinghua.edu.cn/simple

网上的教程有一种解决超时报错的方法,就是通过延长加载时间来完成第三方库的下载,亲测不好用。在漫长的等待后看到报错,你会觉得自己像个傻¥。直接换源会比较开心~ (∩_∩)

基本上,经过上述一波操作之后,Python的第三方库已经可以正常安装了,这个时候你可能会在安装成功的提示后面看到这样几行内容:

You are using pip version 18.1, however version 19.0.3 is available.
You should consider upgrading via the ‘python -m pip install --upgrade pip’ command.

不妨跟着提示更新一下自己的pip版本:

C:\>Python37\python -m pip install --upgrade pip

如果出现超时报错的情况,就换源再继续操作:

C:\>Python37\python -m pip install --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple

Installing collected packages: pip
Found existing installation: pip 18.1
Uninstalling pip-18.1:
Successfully uninstalled pip-18.1
Successfully installed pip-19.0.3

本篇完结撒花~

猜你喜欢

转载自blog.csdn.net/Jianshu_Wang/article/details/88643218