使用pip管理包
pip 是 Python 的一个包管理工具,用于安装、升级和移除软件包。pip 默认从 Python Package Index(PyPI)安装软件包,可以在浏览器中访问 PyPI 来查看可用的软件包。除了安装软件包之外,pip 还提供了许多其他命令,例如子命令: “install”, “uninstall”, “freeze” 等等。
通过指定包的名称来安装最新版本的包:
(tutorial-env) $ python -m pip install novas Collecting novas Downloading novas-3.1.1.3.tar.gz (136kB) Installing collected packages: novas Running setup.py install for novas Successfully installed novas-3.1.1.3
通过提供包名称后跟 == 和版本号来安装特定版本的包:
(tutorial-env) $ python -m pip install requests==2.6.0 Collecting requests==2.6.0 Using cached requests-2.6.0-py2.py3-none-any.whl Installing collected packages: requests Successfully installed requests-2.6.0
如果重新运行这个命令,pip 会注意到已经安装了所请求的版本因而不做任何事。 可以提供不同的版本号来获取相应版本,或者可以运行 python -m pip install –upgrade 以将软件包升级到最新版本:
(tutorial-env) $ python -m pip install --upgrade requests Collecting requests Installing collected packages: requests Found existing installation: requests 2.6.0 Uninstalling requests-2.6.0: Successfully uninstalled requests-2.6.0 Successfully installed requests-2.7.0
python -m pip uninstall 后跟一个或多个要从虚拟环境中删除的包所对应的名称。
python -m pip show 将显示有关某个特定包的信息:
(tutorial-env) $ python -m pip show requests --- Metadata-Version: 2.0 Name: requests Version: 2.7.0 Summary: Python HTTP for Humans. Home-page: http://python-requests.org Author: Kenneth Reitz Author-email: me@kennethreitz.com License: Apache 2.0 Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages Requires:
python -m pip list 将显示所有在虚拟环境中安装的包:
(tutorial-env) $ python -m pip list novas (3.1.1.3) numpy (1.9.2) pip (7.0.3) requests (2.7.0) setuptools (16.0)
python -m pip freeze 将产生一个类似的已安装包列表,但其输出会使用 python -m pip install 所期望的格式。 一个常见的约定是将此列表放在 requirements.txt 文件中:
(tutorial-env) $ python -m pip freeze > requirements.txt (tutorial-env) $ cat requirements.txt novas==3.1.1.3 numpy==1.9.2 requests==2.7.0
然后可以将 requirements.txt 提交给版本控制并作为应用程序的一部分提供。然后用户可以使用 install -r 安装所有必需的包:
(tutorial-env) $ python -m pip install -r requirements.txt Collecting novas==3.1.1.3 (from -r requirements.txt (line 1)) ... Collecting numpy==1.9.2 (from -r requirements.txt (line 2)) ... Collecting requests==2.7.0 (from -r requirements.txt (line 3)) ... Installing collected packages: novas, numpy, requests Running setup.py install for novas Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0