使用pip安装python包

Pip 是安装python包的工具,提供了安装包,列出已经安装的包,升级包以及卸载包的功能。

ubutu下安装pip命令:sudo apt-get install python-pip

1 pip使用详解

  • pip安装包
1
2
3
4
5
6
7
8
9
10
安装包
pip install SomePackage
[...]
Successfully installed SomePackage
 
指定版本号安装
(sudo) pip install Django==1.8.3
 
一次安装多个
(sudo) pip install BeautifulSoup4 fabric virtualenv

如果需要安装的包比较多的时候,这样做会比较繁琐,我们还有一键安装的方法。首先新建一个文本文件,如:requirements.txt,然后将你需要安装的包名保存到该文件中(根据自己的需要),如下:

1
2
3
4
5
6
7
8
9
10
11
Babel==1.3
Flask==0.10.1
Flask-Login==0.2.7
Flask-SQLAlchemy==1.0
Flask-WTF==0.9.3
Jinja2==2.7.1
SQLAlchemy==0.8.2
WTForms==1.0.5
Werkzeug==0.9.4
psycopg2==2.5.1
...

最后你只需要输入以下命令,所有需要的包就可以全部安装好了:

1
$ pip install -r requirements.txt

如果没有出现错误,祝贺你:安装成功了。

  • pip查看已安装的包的信息
1
2
3
4
5
6
7
# pip show --files SomePackage
Name: SomePackage
Version: 1.0
Location: /my/env/lib/pythonx.x/site-packages
Files:
../somepackage/__init__.py
[...]
  • 查看当前环境中都安装了哪些包$ pip freeze

  • pip检查哪些包需要更新

1
2
# pip list --outdated
SomePackage (Current: 1.0 Latest: 2.0)
  • pip升级包
1
2
3
4
5
6
7
# pip install --upgrade SomePackage
[...]
Found existing installation: SomePackage 1.0
Uninstalling SomePackage:
Successfully uninstalled SomePackage
Running setup.py install for SomePackage
Successfully installed SomePackage
  • pip卸载包
1
2
3
4
5
$ (sudo) pip uninstall SomePackage
Uninstalling SomePackage:
/my/env/lib/pythonx.x/site-packages/somepackage
Proceed (y/n)? y
Successfully uninstalled SomePackage
  • 导出当前系统中已经安装的包信息
    1
    pip freeze > requirements.txt

2 pip使用实例

  • 安装redis

    1
    (sudo)pip install redis
  • 卸载redis

1
2
3
4
5
6
# pip uninstall redis
Uninstalling redis:
/usr/lib/python2.6/site-packages/redis-2.9.1-py2.6.egg-info
.....省略一些内容....
Proceed (y/n)? y
Successfully uninstalled redis
  • 查看待更新包
1
2
3
4
pip list --outdate
pygpgme (Current: 0.1 Latest: 0.3)
pycurl (Current: 7.19.0 Latest: 7.19.3.1)
iniparse (Current: 0.3.1 Latest: 0.4)

3 pip参数解释

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
27
28
29
$ pip --help
Usage:
pip <command> [options]
Commands:
install 安装包.
uninstall 卸载包.
freeze 按着一定格式输出已安装包列表
list 列出已安装包.
show 显示包详细信息.
search 搜索包,类似yum里的search.
wheel Build wheels from your requirements.
zip 不推荐. Zip individual packages.
unzip 不推荐. Unzip individual packages.
bundle 不推荐. Create pybundles.
help 当前帮助.
General Options:
-h, --help 显示帮助.
-v, --verbose 更多的输出,最多可以使用3次
-V, --version 现实版本信息然后退出.
-q, --quiet 最少的输出.
--log-file <path> 覆盖的方式记录verbose错误日志,默认文件:/root/.pip/pip.log
--log <path> 不覆盖记录verbose输出的日志.
--proxy <proxy> Specify a proxy in the form [user:passwd@]proxy.server:port.
--timeout <sec> 连接超时时间 (默认15秒).
--exists-action <action> Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup.
--cert <path> 证书.