1. 程式人生 > 程式設計 >Python開發之pip安裝及使用方法詳解

Python開發之pip安裝及使用方法詳解

pip是什麼

其實,pip就是 Python標準庫(The Python Standard Library)中的一個包,這個包比較特殊,用它可以來管理Python標準庫(The Python Standard Library)中其他的包。pip支援從PyPI(https://pypi.org/ ),版本控制,本地專案以及直接從分發檔案進行安裝。pip是一個命令列程式。 安裝pip後,會向系統新增一個pip命令,該命令可以從命令提示符執行。

目前,pip 是The Python Packaging Authority (PyPA) 推薦的 Python 包管理工具!

The Python Packaging Authority (PyPA) is a working group that maintains many of the relevant projects in Python packaging.

pip安裝

從 Python 2 版本 >=2.7.9 或 Python 3 版本 >=3.4 開始,官網的安裝包中已經自帶了 pip,在安裝時使用者可以直接選擇安裝。或者如果使用由 virtualenv 或者 pyvenv 建立的 Virtual Environment,那麼 pip 也是被預設安裝的。

如果沒有在安裝python時候,選擇上"安裝pip"選項,那麼也可以從本地安裝。例如,直接使用get-pip.py進行安裝。

首先從官網下載get-pip.py;

然後直接執行python get-pip.py即可;

pip使用

安裝後,在命令列中鍵入:pip+ 回車,就會出現如下使用說明:

Usage:
 pip <command> [options]

Commands:
 install           Install packages.
 download          Download packages.
 uninstall          Uninstall packages.
 freeze           Output installed packages in requirements format.
 list            List installed packages.
 show            Show information about installed packages.
 check            Verify installed packages have compatible dependencies.
 config           Manage local and global configuration.
 search           Search PyPI for packages.
 wheel            Build wheels from your requirements.
 hash            Compute hashes of package archives.
 completion         A helper command used for command completion.
 help            Show help for commands.

General Options:
 -h,--help         Show help.
 --isolated         Run pip in an isolated mode,ignoring environment variables and user configuration.
 -v,--verbose        Give more output. Option is additive,and can be used up to 3 times.
 -V,--version        Show version and exit.
 -q,--quiet         Give less output. Option is additive,and can be used up to 3 times (corresponding to
               WARNING,ERROR,and CRITICAL logging levels).
 --log <path>        Path to a verbose appending log.
 --proxy <proxy>       Specify a proxy in the form [user:passwd@]proxy.server:port.
 --retries <retries>     Maximum number of retries each connection should attempt (default 5 times).
 --timeout <sec>       Set the socket timeout (default 15 seconds).
 --exists-action <action>  Default action when a path already exists: (s)witch,(i)gnore,(w)ipe,(b)ackup,(a)bort).
 --trusted-host <hostname>  Mark this host as trusted,even though it does not have valid or any HTTPS.
 --cert <path>        Path to alternate CA bundle.
 --client-cert <path>    Path to SSL client certificate,a single file containing the private key and the
               certificate in PEM format.
 --cache-dir <dir>      Store the cache data in <dir>.
 --no-cache-dir       Disable the cache.
 --disable-pip-version-check
               Don't periodically check PyPI to determine whether a new version of pip is available for
               download. Implied with --no-index.
 --no-color         Suppress colored output

pip命令組合比較靈活,下面重點介紹幾個。

install

命令列直接鍵入pip install + 回車,則 出現如下提示:ERROR: You must give at least one requirement to install (see "pip help install")。接著我們鍵入pip help install,就會出現pip install的使用說明了,如下:

Usage:
 pip install [options] <requirement specifier> [package-index-options] ...
 pip install [options] -r <requirements file> [package-index-options] ...
 pip install [options] [-e] <vcs project url> ...
 pip install [options] [-e] <local project path> ...
 pip install [options] <archive url/path> ...

Description:
 Install packages from:

 - PyPI (and other indexes) using requirement specifiers.
 - VCS project urls.
 - Local project directories.
 - Local or remote source archives.

 pip also supports installing from "requirements files",which provide
 an easy way to specify a whole environment to be installed.

Install Options:
 -r,--requirement <file>  Install from the given requirements file. This option can be used multiple times.
 -c,--constraint <file>   Constrain versions using the given constraints file. This option can be used multiple times.
 --no-deps          Don't install package dependencies.
 --pre            Include pre-release and development versions. By default,pip only finds stable versions.
 -e,--editable <path/url>  Install a project in editable mode (i.e. setuptools "develop mode") from a local project path or a
               VCS url.
 -t,--target <dir>     Install packages into <dir>. By default this will not replace existing files/folders in <dir>. Use
               --upgrade to replace existing packages in <dir> with new versions.
 --platform <platform>    Only use wheels compatible with <platform>. Defaults to the platform of the running system.
 --python-version <python_version>
               Only use wheels compatible with Python interpreter version <version>. If not specified,then the
               current system interpreter minor version is used. A major version (e.g. '2') can be specified to
               match all minor revs of that major version. A minor version (e.g. '34') can also be specified.
 --implementation <implementation>
               Only use wheels compatible with Python implementation <implementation>,e.g. 'pp','jy','cp',or
               'ip'. If not specified,then the current interpreter implementation is used. Use 'py' to force
               implementation-agnostic wheels.
 --abi <abi>         Only use wheels compatible with Python abi <abi>,e.g. 'pypy_41'. If not specified,then the
               current interpreter abi tag is used. Generally you will need to specify --implementation,--platform,and --python-version when using this option.
 --user           Install to the Python user install directory for your platform. Typically ~/.local/,or
               %APPDATA%\Python on Windows. (See the Python documentation for site.USER_BASE for full details.)
 --root <dir>        Install everything relative to this alternate root directory.
 --prefix <dir>       Installation prefix where lib,bin and other top-level folders are placed
 -b,--build <dir>      Directory to unpack packages into and build in. Note that an initial build still takes place in a
               temporary directory. The location of temporary directories can be controlled by setting the TMPDIR
               environment variable (TEMP on Windows) appropriately. When passed,build directories are not
               cleaned in case of failures.
 --src <dir>         Directory to check out editable projects into. The default in a virtualenv is "<venv path>/src".
               The default for global installs is "<current dir>/src".
 -U,--upgrade        Upgrade all specified packages to the newest available version. The handling of dependencies
               depends on the upgrade-strategy used.
 --upgrade-strategy <upgrade_strategy>
               Determines how dependency upgrading should be handled [default: only-if-needed]. "eager" -
               dependencies are upgraded regardless of whether the currently installed version satisfies the
               requirements of the upgraded package(s). "only-if-needed" - are upgraded only when they do not
               satisfy the requirements of the upgraded package(s).
 --force-reinstall      Reinstall all packages even if they are already up-to-date.
 -I,--ignore-installed   Ignore the installed packages (reinstalling instead).
 --ignore-requires-python  Ignore the Requires-Python information.
 --no-build-isolation    Disable isolation when building a modern source distribution. Build dependencies specified by PEP
               518 must be already installed if this option is used.
 --install-option <options> Extra arguments to be supplied to the setup.py install command (use like --install-option="--
               install-scripts=/usr/local/bin"). Use multiple --install-option options to pass multiple options
               to setup.py install. If you are using an option with a directory path,be sure to use absolute
               path.
 --global-option <options>  Extra global options to be supplied to the setup.py call before the install command.
 --compile          Compile Python source files to bytecode
 --no-compile        Do not compile Python source files to bytecode
 --no-warn-script-location  Do not warn when installing scripts outside PATH
 --no-warn-conflicts     Do not warn about broken dependencies
 --no-binary <format_control>
               Do not use binary packages. Can be supplied multiple times,and each time adds to the existing
               value. Accepts either :all: to disable all binary packages,:none: to empty the set,or one or
               more package names with commas between them. Note that some packages are tricky to compile and may
               fail to install when this option is used on them.
 --only-binary <format_control>
               Do not use source packages. Can be supplied multiple times,and each time adds to the existing
               value. Accepts either :all: to disable all source packages,or one or
               more package names with commas between them. Packages without binary distributions will fail to
               install when this option is used on them.
 --prefer-binary       Prefer older binary packages over newer source packages.
 --no-clean         Don't clean up build directories.
 --require-hashes      Require a hash to check each requirement against,for repeatable installs. This option is implied
               when any package in a requirements file has a --hash option.
 --progress-bar <progress_bar>
               Specify type of progress to be displayed [off|on|ascii|pretty|emoji] (default: on)

Package Index Options:
 -i,--index-url <url>    Base URL of Python Package Index (default https://pypi.org/simple). This should point to a
               repository compliant with PEP 503 (the simple repository API) or a local directory laid out in the
               same format.
 --extra-index-url <url>   Extra URLs of package indexes to use in addition to --index-url. Should follow the same rules as
               --index-url.
 --no-index         Ignore package index (only looking at --find-links URLs instead).
 -f,--find-links <url>   If a url or path to an html file,then parse for links to archives. If a local path or file:// url
               that's a directory,then look for archives in the directory listing.
 --process-dependency-links Enable the processing of dependency links.

General Options:
 -h,and can be used up to 3 times (corresponding to WARNING,a single file containing the private key and the certificate in
               PEM format.
 --cache-dir <dir>      Store the cache data in <dir>.
 --no-cache-dir       Disable the cache.
 --disable-pip-version-check
               Don't periodically check PyPI to determine whether a new version of pip is available for download.
               Implied with --no-index.
 --no-color         Suppress colored output

上面一大堆,總結來說,安裝命令就是:pip install <包名> 或 pip install -r requirements.txt(對於本地安裝包可以指定路徑)。唯一需要特殊說明的是,安裝時可以指定版本號來安裝,舉例如下:

pip install SomePackage       # 最新版本
pip install SomePackage==1.0.4    # 指定版本
pip install 'SomePackage>=1.0.4'   # 最小版本

uninstall

解除安裝安裝包命令:pip uninstall <包名> 或 pip uninstall -r requirements.txt

升級包

pip install -U <包名> 或:pip install <包名> --upgrade

freeze

pip freeze,檢視已經安裝的包及版本資訊。匯出到指定檔案中,如圖,注意 “ > ”,檔名稱隨意。常見按第二種寫法。

list

列出當前已經安裝的包。使用命令pip list -o則可查詢可升級的包。

Python開發之pip安裝及使用方法詳解

show

顯示包所在目錄及資訊,格式為:pip show <包名>。如果不加包名,則提示ERROR: Please provide a package name or names.。

Python開發之pip安裝及使用方法詳解

search

搜尋包,格式為:pip search <搜尋關鍵字>。如果不寫關鍵字,則提示ERROR: Missing required argument (search query).。

Python開發之pip安裝及使用方法詳解

更多關於pip安裝及使用方法請檢視下面的相關連結