pythonista_什么是点子? 新Pythonista指南

pythonista

What is pip? pip is the standard package manager for Pyhon. It allows you to install and manage additional packages that are not part of the Python standard library. This tutorial is an introduction to pip for new Pythonistas.

什么是pip pip是Pyhon的标准软件包管理器。 它允许您安装和管理不属于Python标准库的其他软件包。 本教程是针对新Pythonista的pip的介绍。

In this tutorial, you’ll learn about:

在本教程中,您将了解:

  • Installing additional packages not included with the standard Python distribution
  • Finding packages published to the Python Package Index (PyPI)
  • Managing requirements for your scripts and applications
  • Uninstalling packages and their dependencies
  • 安装标准Python发行版中未包含的其他软件包
  • 查找发布到Python软件包索引 ( PyPI )的软件包
  • 管理脚本和应用程序的需求
  • 卸载软件包及其依赖项

As you’ll see, the Python community is very active and has created some neat alternatives to pip that you’ll learn about later in this tutorial.

如您所见,Python社区非常活跃,并且为pip创建了一些精巧的替代方法,您将在本教程的后面部分中学习这些替代方法。

Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.

免费奖金: 关于Python精通的5个想法 ,这是针对Python开发人员的免费课程,向您展示了将Python技能提升到新水平所需的路线图和心态。

pip入门 (Getting Started With pip)

So, what is pip? pip is a package manager for Python. That means it’s a tool that allows you to install and manage additional libraries and dependencies that are not distributed as part of the standard library.

那么,什么是点子? pip是Python的软件包管理器。 这意味着它是一个允许您安装和管理未作为标准库的一部分分发的其他库和依赖项的工具。

Package management is so important that pip has been included with the Python installer since versions 3.4 for Python 3 and 2.7.9 for Python 2, and it’s used by many Python projects, which makes it an essential tool for every Pythonista.

软件包管理非常重要,自从Python 3的3.4版本和Python 2的2.7.9版本以来, pip已包含在Python安装程序中,并且它被许多Python项目使用,这使其成为每个Pythonista的必备工具。

The concept of a package manager might be familiar to you if you are coming from other languages. JavaScript uses npm for package management, Ruby uses gem, and .NET use NuGet. In Python, pip has become the standard package manager.

如果您来自其他语言,则可能会熟悉软件包管理器的概念。 JavaScript使用npm进行软件包管理, Ruby使用gem , .NET使用NuGet 。 在Python中, pip已成为标准的程序包管理器。

The Python installer installs pip, so it should be ready for you to use, unless you installed an old version of Python. You can verify that pip is available by running the following command in your console:

Python安装程序会安装pip ,因此除非您安装了旧版本的Python,否则应该可以使用。 您可以通过在控制台中运行以下命令来验证pip可用:

 $ pip --version

$ pip --version

pip 18.1 from C:Python37libsite-packagespip (python 3.7)
pip 18.1 from C:Python37libsite-packagespip (python 3.7)

You should see a similar output displaying the pip version, as well as the location and version of Python. If you are using an old version of Python that does not include pip, then you can install it by following the instructions for your system in the pip installation documentation.

您应该会看到类似的输出,显示pip版本以及Python的位置和版本。 如果您使用的旧版本的Python不包含pip ,则可以按照pip安装文档中系统的说明进行安装 。

You probably want to follow the examples in this tutorial inside a virtual environment to avoid installing packages to the global Python installation. You can learn about virtual environments in Python Virtual Environments: A Primer. The Using Virtual Environments section of that article explains the basics of creating new virtual environments.

您可能希望在虚拟环境中遵循本教程中的示例,以避免将软件包安装到全局Python安装中。 您可以在Python Virtual Environments:A Primer中了解虚拟环境。 该文章的“ 使用虚拟环境”部分介绍了创建新虚拟环境的基础。

pip安装软件包 (Installing Packages With pip)

Python is considered a batteries included language. This means that the Python standard library includes an extensive set of packages and modules to help developers with their scripts and applications.

Python被认为是电池包含的语言。 这意味着Python标准库包括一组广泛的软件包和模块,以帮助开发人员使用其脚本和应用程序。

At the same time, Python has a very active community that contributes an even bigger set of packages that can help you with your development needs. These packages are published to the Python Package Index, also known as PyPI (pronounced Pie Pea Eye). PyPI hosts an extensive collection of packages that include development frameworks, tools, and libraries.

同时,Python有一个非常活跃的社区,它贡献了更多的软件包,可以帮助您满足开发需求。 这些软件包已发布到Python软件包索引 (也称为PyPI (发音为Pie Pea Eye))中。 PyPI托管了许多软件包,其中包括开发框架,工具和库。

Many of these packages simplify Python development by providing friendly interfaces to functionality that already exists in the standard library. For example, you can write a script that retrieves the contents of a web page using only the standard libraries included with Python:

这些软件包中的许多软件包都通过提供标准库中已有功能的友好接口来简化Python开发。 例如,您可以编写仅使用Python随附的标准库来检索网页内容的脚本:

In this script, you import cgi and http.client, both of which are included in the Python standard library. You create an HTTPSConnection object specifying the server and invoke its .request() and .getresponse() to retrieve a response.

在此脚本中,导入cgihttp.client ,这两个都包含在Python标准库中。 您创建一个指定服务器的HTTPSConnection对象,并调用其.request().getresponse()来检索响应。

From the response, you can retrieve the Content-Type header and parse it using the cgi module to extract the charset in which the page is encoded.

从响应中,您可以检索Content-Type标头并使用cgi模块对其进行解析,以提取对页面进行编码的字符集。

cgi.parse_header() returns a tuple with a main value and a dictionary of parameters. For example, the Content-Type header might contain a value like text/html; charset=ISO-8859-1.

cgi.parse_header()返回具有主值和参数字典的元组。 例如, Content-Type标头可能包含text/html; charset=ISO-8859-1类的值text/html; charset=ISO-8859-1 text/html; charset=ISO-8859-1

The tuple will contain the string text/html as the first element, and the second element will be a dictionary in the form {'charset': 'ISO-8859-1'}. Because you only care about the charset parameter, you can ignore the beginning of the tuple using an underscore: _, params = cgi.parse_header(content_type).

元组将包含字符串text/html作为第一个元素,第二个元素将是形式为{'charset': 'ISO-8859-1'}的字典。 因为只关心charset参数,所以可以使用下划线忽略元组的开头: _, params = cgi.parse_header(content_type)

Note: The Meaning of Underscores in Python explains how to use underscores to unpack values from a tuple.

注意: Python中的下划线含义解释了如何使用下划线从元组中解包值。

Once you have the encoding of the page, you can read the response and decode it into text. You can run the example in the console to see how it works:

对页面进行编码后,您可以读取响应并将其解码为文本。 您可以在控制台中运行示例以查看其工作方式:

 $ python using-http.py

$ python using-http.py

Response returned: 200 (OK)
Response returned: 200 (OK)
Body:
Body:


lang="en">lang="en">webpages, images, videos and more. Google has many special features to help you 
webpages, images, videos and more. Google has many special features to help you 
find exactly what you're looking for." name="description">
find exactly what you're looking for." name="description">
name="robots">... Additional Output Omitted
name="robots">... Additional Output Omitted

This seems like a lot of work for a small script that retrieves the contents of a web page. Fortunately, there is a Python package that simplifies HTTP requests and provides a nice interface to do exactly what you want.

对于检索网页内容的小脚本来说,这似乎是很多工作。 幸运的是,有一个Python软件包可以简化HTTP请求,并提供一个不错的接口来准确执行您想要的操作。

基本软件包安装 (Basic Package Installation)

PyPI hosts a very popular library to perform HTTP requests called requests. You can learn all about it in its official documentation site.

PyPI托管一个非常流行的库来执行称为requests HTTP requests 您可以在其官方文档站点上了解所有相关信息。

The first step is to install the requests package into your environment. You can learn about pip supported commands by running it with help:

第一步是将requests包安装到您的环境中。 您可以通过运行help来了解pip支持的命令:

As you can see, pip provides an install command to install packages. You can run it to install the requests package:

如您所见, pip提供了一个install命令来安装软件包。 您可以运行它来安装requests包:

 $ pip install requests

$ pip install requests

Looking in indexes: https://pypi.org/simple
Looking in indexes: https://pypi.org/simple
Collecting requests
Collecting requests
  Using cached 
  Using cached 
  https://files.pythonhosted.org/packages/7d/e3/
  https://files.pythonhosted.org/packages/7d/e3/
  20f3d364d6c8e5d2353c72a67778eb189176f08e873c9900e10c0287b84b/
  20f3d364d6c8e5d2353c72a67778eb189176f08e873c9900e10c0287b84b/
  requests-2.21.0-py2.py3-none-any.whl
  requests-2.21.0-py2.py3-none-any.whl
Collecting chardet<3.1.0,>=3.0.2 (from requests)
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Using cached https://files.pythonhosted.org/packages/bc/a9/
  Using cached https://files.pythonhosted.org/packages/bc/a9/
  01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/
  01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/
  chardet-3.0.4-py2.py3-none-any.whl
  chardet-3.0.4-py2.py3-none-any.whl
Collecting idna<2.9,>=2.5 (from requests)
Collecting idna<2.9,>=2.5 (from requests)
  Using cached https://files.pythonhosted.org/packages/14/2c/
  Using cached https://files.pythonhosted.org/packages/14/2c/
  cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/
  cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/
  idna-2.8-py2.py3-none-any.whl
  idna-2.8-py2.py3-none-any.whl
Collecting urllib3<1.25,>=1.21.1 (from requests)
Collecting urllib3<1.25,>=1.21.1 (from requests)
  Using cached https://files.pythonhosted.org/packages/62/00/
  Using cached https://files.pythonhosted.org/packages/62/00/
  ee1d7de624db8ba7090d1226aebefab96a2c71cd5cfa7629d6ad3f61b79e/
  ee1d7de624db8ba7090d1226aebefab96a2c71cd5cfa7629d6ad3f61b79e/
  urllib3-1.24.1-py2.py3-none-any.whl
  urllib3-1.24.1-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests)
Collecting certifi>=2017.4.17 (from requests)
  Using cached https://files.pythonhosted.org/packages/9f/e0/
  Using cached https://files.pythonhosted.org/packages/9f/e0/
  accfc1b56b57e9750eba272e24c4dddeac86852c2bebd1236674d7887e8a/
  accfc1b56b57e9750eba272e24c4dddeac86852c2bebd1236674d7887e8a/
  certifi-2018.11.29-py2.py3-none-any.whl
  certifi-2018.11.29-py2.py3-none-any.whl
Installing collected packages: chardet, idna, urllib3, certifi, requests
Installing collected packages: chardet, idna, urllib3, certifi, requests
Successfully installed certifi-2018.11.29 chardet-3.0.4 idna-2.8 
Successfully installed certifi-2018.11.29 chardet-3.0.4 idna-2.8 
  requests-2.21.0 urllib3-1.24.1
  requests-2.21.0 urllib3-1.24.1
You are using pip version 18.1, however version 19.0.1 is available.
You are using pip version 18.1, however version 19.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' 
You should consider upgrading via the 'python -m pip install --upgrade pip' 
  command.
  command.

You should see an output similar to the one above. You use pip with an install command followed by the name of the package you want to install. pip looks for the package in PyPI, calculates its dependencies, and installs them to insure requests will work.

您应该看到类似于上面的输出。 您可以将pipinstall命令一起使用,后跟要安装的软件包的名称。 pip在PyPI中查找软件包,计算其依赖性,然后安装它们以确保requests能够正常工作。

You can also see that the current environment is using pip version 18.1, but version 19.0.1 is available. It also shows the command you should use to update pip, so let’s do that:

您还可以看到当前环境正在使用pip版本18.1 ,但是版本19.0.1可用。 它还显示了您应该用来更新pip的命令,所以让我们这样做:

Notice that you use python -m to update pip. The -m switch tells Python to run a module as an executable. This is necessary because in order for you to update pip, the old version has to be uninstalled before installing the new version, and removing it while running the tool can cause errors.

注意,您使用python -m更新pip -m开关告诉Python将模块作为可执行文件运行。 这是必要的,因为为了更新pip ,必须先卸载旧版本,然后再安装新版本,并且在运行该工具时将其删除可能会导致错误。

When you run pip as a module, Python loads the module in memory and allows the package to be removed while it is being used. You can run packages as if they were scripts if the package provides a top-level script __main__.py.

当您将pip作为模块运行时,Python会将模块加载到内存中,并允许在使用包时将其删除。 如果软件包提供了顶级脚本 __main__.py ,则可以将其作为脚本运行。

Now that you have installed requests and upgraded pip, you can use the list command to see the packages installed in your environment:

现在,您已经安装了requests并升级了pip ,您可以使用list命令查看您的环境中安装的软件包:

 $ pip list

$ pip list

Package    Version
Package    Version
---------- ----------
---------- ----------
certifi    2018.11.29
certifi    2018.11.29
chardet    3.0.4
chardet    3.0.4
idna       2.8
idna       2.8
pip        19.0.1
pip        19.0.1
requests   2.21.0
requests   2.21.0
setuptools 40.6.2
setuptools 40.6.2
urllib3    1.24.1
urllib3    1.24.1

As you can see, pip has been upgraded to version 19.0.1 (the latest version at the moment), and requests version 2.21.0 has been installed.

如您所见, pip已升级到版本19.0.1 (目前是最新版本),并已requests安装版本2.21.0

The pip install command always looks for the latest version of the package and installs it. It also searches for dependencies listed in the package metadata and installs those dependencies to insure that the package has all the requirements it needs.

pip install 命令始终会寻找pip install 的最新版本并进行安装。 它还搜索包元数据中列出的依赖项,并安装这些依赖项以确保包具有其所需的所有要求。

As you can see, multiple packages were installed. You can look at the package metadata by using the show command in pip:

如您所见,已安装了多个软件包。 您可以使用pipshow命令查看软件包元数据:

The metadata lists certifi, chardet, idna, and urllib3 as dependencies, and you can see they were also installed.

元数据将certifichardetidnaurllib3列为依赖项,您可以看到它们也已安装。

With the requests package installed, you can modify the example above and see how easy it is to retrieve the contents of a web page:

安装了requests包后,您可以修改上面的示例,并查看检索网页内容有多么容易:

 # In using-requests.py

# In using-requests.py

import import requests

requests

url url = = 'https://www.google.com'
'https://www.google.com'
response response = = requestsrequests .. getget (( urlurl )
)
printprint (( ff 'Response returned: 'Response returned:  {response.status_code}{response.status_code} , ,  {response.reason}{response.reason} '' )
)
printprint (( responseresponse .. texttext )
)

You can import the requests package as any other standard package because it is now installed in your environment.

您可以将requests包导入为任何其他标准包,因为它已安装在您的环境中。

As you can see, requests.get() handles the HTTP connection for you and returns a response object similar to the original example but with some interface improvements.

如您所见, requests.get()为您处理HTTP连接,并返回与原始示例类似的响应对象,但对接口进行了一些改进。

You don’t have to deal with the encoding of the page because requests will handle that for you in most situations. Still, requests provides a flexible interface to handle special cases through the requests.Response object.

您不必处理页面的编码,因为在大多数情况下requests将为您处理。 仍然, requests提供了一个灵活的接口来通过requests.Response对象处理特殊情况。

使用需求文件 (Using Requirement Files)

The pip install command always installs the latest published version of a package, but sometimes, you may want to install a specific version that you know works with your code.

pip install命令始终会安装软件包的最新发布版本,但是有时,您可能希望安装可以与代码一起使用的特定版本。

You want to create a specification of the dependencies and versions you used to develop and test your application, so there are no surprises when you use the application in production.

您要创建用于开发和测试应用程序的依赖项和版本的规范,因此在生产环境中使用该应用程序时不会感到惊讶。

Requirement files allow you to specify exactly which packages and versions should be installed. Running pip help shows that there is a freeze command that outputs the installed packages in requirements format. You can use this command, redirecting the output to a file to generate a requirements file:

需求文件使您可以准确指定应安装的软件包和版本。 运行pip help显示有一个freeze命令,该命令以需求格式输出已安装的软件包。 您可以使用以下命令,将输出重定向到文件以生成需求文件:

The freeze command dumps all the packages and their versions to standard output, so you can redirect the output to a file that can be used to install the exact requirements into another system. The convention is to name this file requirements.txt, but you can give it any name you want.

freeze命令将所有软件包及其版本转储到标准输出,因此您可以将输出重定向到一个文件,该文件可用于将确切的要求安装到另一个系统中。 约定是将此文件命名为requirements.txt ,但是您可以根据需要命名。

When you want to replicate the environment in another system, you can run pip install specifying the requirements file using the -r switch:

要在另一个系统中复制环境时,可以使用-r开关运行pip install指定需求文件:

 $ pip install -r requirements.txt

$ pip install -r requirements.txt

Looking in indexes: https://pypi.org/simple
Looking in indexes: https://pypi.org/simple
Collecting certifi==2018.11.29 (from -r .requirements.txt (line 1))
Collecting certifi==2018.11.29 (from -r .requirements.txt (line 1))
  Using cached https://files.pythonhosted.org/packages/9f/e0/
  Using cached https://files.pythonhosted.org/packages/9f/e0/
  accfc1b56b57e9750eba272e24c4dddeac86852c2bebd1236674d7887e8a/
  accfc1b56b57e9750eba272e24c4dddeac86852c2bebd1236674d7887e8a/
  certifi-2018.11.29-py2.py3-none-any.whl
  certifi-2018.11.29-py2.py3-none-any.whl
Collecting chardet==3.0.4 (from -r .requirements.txt (line 2))
Collecting chardet==3.0.4 (from -r .requirements.txt (line 2))
  Using cached https://files.pythonhosted.org/packages/bc/a9/
  Using cached https://files.pythonhosted.org/packages/bc/a9/
  01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/
  01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/
  chardet-3.0.4-py2.py3-none-any.whl
  chardet-3.0.4-py2.py3-none-any.whl
Collecting idna==2.8 (from -r .requirements.txt (line 3))
Collecting idna==2.8 (from -r .requirements.txt (line 3))
  Using cached https://files.pythonhosted.org/packages/14/2c/
  Using cached https://files.pythonhosted.org/packages/14/2c/
  cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/
  cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/
  idna-2.8-py2.py3-none-any.whl
  idna-2.8-py2.py3-none-any.whl
Collecting requests==2.21.0 (from -r .requirements.txt (line 4))
Collecting requests==2.21.0 (from -r .requirements.txt (line 4))
  Using cached https://files.pythonhosted.org/packages/7d/e3/
  Using cached https://files.pythonhosted.org/packages/7d/e3/
  20f3d364d6c8e5d2353c72a67778eb189176f08e873c9900e10c0287b84b/
  20f3d364d6c8e5d2353c72a67778eb189176f08e873c9900e10c0287b84b/
  requests-2.21.0-py2.py3-none-any.whl
  requests-2.21.0-py2.py3-none-any.whl
Collecting urllib3==1.24.1 (from -r .requirements.txt (line 5))
Collecting urllib3==1.24.1 (from -r .requirements.txt (line 5))
  Using cached https://files.pythonhosted.org/packages/62/00/
  Using cached https://files.pythonhosted.org/packages/62/00/
  ee1d7de624db8ba7090d1226aebefab96a2c71cd5cfa7629d6ad3f61b79e/
  ee1d7de624db8ba7090d1226aebefab96a2c71cd5cfa7629d6ad3f61b79e/
  urllib3-1.24.1-py2.py3-none-any.whl
  urllib3-1.24.1-py2.py3-none-any.whl
Installing collected packages: certifi, chardet, idna, urllib3, requests
Installing collected packages: certifi, chardet, idna, urllib3, requests
Successfully installed certifi-2018.11.29 chardet-3.0.4 idna-2.8 
Successfully installed certifi-2018.11.29 chardet-3.0.4 idna-2.8 
  requests-2.21.0 urllib3-1.24.1
  requests-2.21.0 urllib3-1.24.1

The versions of the packages will match those listed in requirements.txt:

软件包的版本将与requirements.txt列出的版本匹配:

You can submit the requirements.txt file into source control and use it to create the exact environment in other machines.

您可以将requirements.txt文件提交到源代码管理中,并使用它在其他计算机上创建确切的环境。

微调要求 (Fine-Tuning Requirements)

The problem with hardcoding the versions of your packages and their dependencies is that packages are updated frequently with bug and security fixes, and you probably want to leverage those as soon as they are published.

对软件包的版本及其依赖项进行硬编码的问题在于,软件包会经常通过错误和安全修复程序进行更新,并且您可能希望在发布后立即利用它们。

The requirements file format allows you to specify dependency versions using logical operators that give you a bit of flexibility to insure packages are updated, but still define the base versions of a package.

需求文件格式允许您使用逻辑运算符指定依赖项版本,这些逻辑运算符使您有一定的灵活性来确保更新软件包,但仍可以定义软件包的基本版本。

Open the requirements.txt file in your favorite editor and make the following changes:

在您喜欢的编辑器中打开requirements.txt文件,并进行以下更改:

 certificertifi >=>= 2018.112018.11 .. 29
29
chardetchardet >=>= 3.03.0 .. 4
4
idnaidna >=>= 2.8
2.8
requestsrequests >=>= 2.212.21 .. 0
0
urllib3urllib3 >=>= 1.241.24 .. 1
1

You can change the logical operator to >= to tell pip to install an exact or greater version that has been published. When you set a new environment using the requirments.txt file, pip looks for the latest version that satisfies the requirement and installs it. You can upgrade the packages in your requirements file by running the install command with the --upgrade switch:

您可以将逻辑运算符更改为>=以告诉pip安装已发布的确切版本或更高版本。 当您使用requirments.txt文件设置新环境时, pip将寻找满足要求的最新版本并进行安装。 您可以通过使用--upgrade开关运行install命令来升级需求文件中的--upgrade

Nothing was upgraded because you have the latest versions, but if a new version was published for a listed package, then the package would’ve been upgraded.

没有任何升级,因为您具有最新版本,但是如果为列出的软件包发布了新版本,则说明该软件包已升级。

In an ideal world, new versions of packages would be backwards compatible and would never introduce new bugs. Unfortunately, new versions can introduce changes that will break your application. The requirements file syntax supports additional version specifiers to fine-tune your requirements.

在理想情况下,新版本的软件包将向后兼容,并且永远不会引入新的错误。 不幸的是,新版本可能会引入更改,从而破坏您的应用程序。 需求文件语法支持其他版本说明符,以微调您的需求。

Let’s say that a new version 3.0 of requests is published but introduces an incompatible change that breaks your application. You can modify the requirements file to prevent 3.0 or higher from being installed:

假设发布了新的3.0requests ,但引入了不兼容的更改,这会破坏您的应用程序。 您可以修改需求文件以防止安装3.0或更高版本:

 certificertifi >=>= 2018.112018.11 .. 29
29
chardetchardet >=>= 3.03.0 .. 4
4
idnaidna >=>= 2.8
2.8
requestsrequests >=>= 2.212.21 .. 00 , , << 3.0
3.0
urllib3urllib3 >=>= 1.241.24 .. 1
1

Changing the version specifier for the requests package ensures that any version greater or equal to 3.0 does not get installed. The pip documentation provides all the information about the requirements file format, and you can consult it to learn more about it.

更改requests包的版本说明符可确保不会安装任何大于或等于3.0版本。 pip文档提供了有关需求文件格式的所有信息,您可以查阅该文件以了解更多信息。

生产与开发的依存关系 (Production vs Development Dependencies)

Not all packages that you install during the development of your applications are going to be application dependencies. There are many packages published to PyPI that are development tools or libraries that you want to leverage during the development process.

并非在应用程序开发期间安装的所有软件包都将成为应用程序依赖项。 有许多发布到PyPI的软件包是您想要在开发过程中利用的开发工具或库。

As an example, you’ll probably want to unit test your application, so you need a unit test framework. A popular framework for unit testing is pytest. You want to install it in your development environment, but you do not want it in your production environment because it isn’t an application dependency.

例如,您可能需要对应用程序进行单元测试,因此需要一个单元测试框架。 pytest是流行的单元测试框架。 您希望将其安装在开发环境中,但不希望将其安装在生产环境中,因为它不是应用程序依赖项。

You create a second requirements file (requirements_dev.txt) to list additional tools to set up a development environment:

您创建第二个需求文件( requirements_dev.txt )列出用于设置开发环境的其他工具:

This requires you to use pip to install both requirement files: requirements.txt and requirements_dev.txt. Fortunately, pip allows you to specify additional parameters within a requirements file. You can modify requirements_dev.txt to also install the requirements from the production requirements.txt file:

这要求您使用pip安装两个需求文件: requirements.txtrequirements_dev.txt 幸运的是,pip允许您在需求文件中指定其他参数。 您可以修改requirements_dev.txt以从生产requirements.txt文件中安装requirements.txt

 # In requirements_dev.txt
# In requirements_dev.txt
-- r r requirementsrequirements .. txt
txt
pytestpytest >=>= 4.24.2 .. 0
0

Notice that you are using the exact same -r switch to install the production requirements.txt file. The requirements file format allows you to specify additional arguments right on a requirements file.

请注意,您正在使用完全相同的-r开关来安装生产requirements.txt文件。 需求文件格式允许您直接在需求文件上指定其他参数。

生产冻结要求 (Freezing Requirements for Production)

You created the production and development requirement files and added them to source control. The files use flexible version specifiers to ensure that you leverage bug fixes published by your dependencies. You are also testing your application and are ready to deploy it to production.

您创建了生产和开发需求文件,并将它们添加到源代码管理中。 这些文件使用灵活的版本说明符,以确保您利用依赖项发布的错误修复程序。 您还将测试您的应用程序,并准备将其部署到生产环境中。

You probably want to ensure that the versions of the dependencies you deploy to production are the exact same versions you used in your integration pipeline or build process because you know all the tests pass and the application works.

您可能要确保部署到生产环境的依赖项版本与您在集成管道或构建过程中使用的版本完全相同,因为您知道所有测试都已通过并且应用程序可以正常工作。

The current version specifiers don’t guarantee that the same versions will be deployed to production, so you want to freeze the production requirements as you saw earlier.

当前的版本说明者不能保证将相同的版本部署到生产环境中,因此您希望像前面看到的那样冻结生产需求。

You create a clean production virtual environment and install the production requirements using the requirements.txt file. Once the requirements are installed, you can freeze the specific versions, dumping the output to a requirements_lock.txt file that you use in production. The requirements_lock.txt file will contain exact versions specifiers and can be used to replicate the environment.

您创建一个干净的生产虚拟环境,并使用requirements.txt文件安装生产需求。 一旦安装了需求,就可以冻结特定的版本,将输出转储到生产中使用的requirements_lock.txt文件中。 requirements_lock.txt文件将包含确切的版本说明符,并可用于复制环境。

查找要使用的软件包 (Finding Packages to Use)

As you become a more experienced Pythonista, there’ll be a set of packages that you’ll know by heart and that you’ll use in most of your applications. The requests and pytest packages are good candidates to become useful tools in your Python toolbox.

随着您成为经验丰富的Pythonista的使用者,将会有一套您将内心知道的软件包,并将在大多数应用程序中使用。 requestspytest软件包是成为Python工具箱中有用工具的理想选择。

There will be times though when you will need to solve a different problem, and you will want to look for a different tool or library that can help you with it. As you can see above, pip help shows that there is a search command that looks for packages published to PyPI.

有时候,您将需要解决其他问题,而您将需要寻找其他可以帮助您解决问题的工具或库。 如上所示, pip help显示了一个search命令,用于查找发布到PyPI的软件包。

Let’s see how this command can help us:

让我们看看该命令如何为我们提供帮助:

The command takes a set of options listed above and a . The query is just a string to search for and will match packages and their descriptions.

该命令采用上面列出的一组选项和 该查询只是一个要搜索的字符串,它将匹配软件包及其描述。

Note: You can use pip help to retrieve additional information about a supported command.

注意:您可以使用pip help 检索有关受支持命令的其他信息。

Let’s say your application needs to access a service that is using OAuth2 for authorization. Ideally, there is a library that works with requests or with a similar interface that can help us. Let’s search PyPI for it using pip:

假设您的应用程序需要访问使用OAuth2进行授权的服务。 理想情况下,有一个可以处理requests或可以帮助我们的类似接口的库。 让我们使用pip搜索PyPI:

 $ pip search requests oauth

$ pip search requests oauth

requests-oauth (0.4.1)             - Hook for adding Open Authentication 
requests-oauth (0.4.1)             - Hook for adding Open Authentication 
                                     support to Python-requests HTTP library.
                                     support to Python-requests HTTP library.
oauth (1.0.1)                      - Library for OAuth version 1.0a.
oauth (1.0.1)                      - Library for OAuth version 1.0a.
pmr2.oauth (0.6.1)                 - OAuth PAS Plugin, OAuth 1.0 provider for 
pmr2.oauth (0.6.1)                 - OAuth PAS Plugin, OAuth 1.0 provider for 
                                     Plone.
                                     Plone.
oauth-proxy (1.0.5)                - OAuth HTTP proxy
oauth-proxy (1.0.5)                - OAuth HTTP proxy
django-oauth (1.1)                 - Support of OAuth in Django.
django-oauth (1.1)                 - Support of OAuth in Django.
intuit-oauth (1.2.0)               - Intuit OAuth Client
intuit-oauth (1.2.0)               - Intuit OAuth Client
brubeck-oauth (0.1.11)             - Brubeck OAuth module
brubeck-oauth (0.1.11)             - Brubeck OAuth module
guillotina-oauth (2.0.0)           - guillotina oauth support
guillotina-oauth (2.0.0)           - guillotina oauth support
httpie-oauth (1.0.2)               - OAuth plugin for HTTPie.
httpie-oauth (1.0.2)               - OAuth plugin for HTTPie.
paytm-oauth (0.2)                  - Consumer for paytm oauth
paytm-oauth (0.2)                  - Consumer for paytm oauth
plurk-oauth (0.9.2)                - Plurk OAuth API
plurk-oauth (0.9.2)                - Plurk OAuth API
oauth-flow (1.0.3)                 - Authenticate and make calls to OAuth 1.0, 
oauth-flow (1.0.3)                 - Authenticate and make calls to OAuth 1.0, 
                                     OAuth 2.0 services
                                     OAuth 2.0 services
... Additional Output Omitted
... Additional Output Omitted

The search term yields quite an extensive collection of packages. Some of them seem specific to a service or technology like django-oauth. Others look promising, like requests-oauth. Unfortunately, there isn’t much information other than a brief description.

搜索词会产生大量的软件包集合。 其中一些似乎特定于服务或技术,例如django-oauth 其他的看起来很有希望,例如requests-oauth 不幸的是,除了简短的描述之外,没有太多其他信息。

Most of the time, you want to search for packages directly in the PyPI website. PyPI provides search capabilities for its index and a way to filter results by the metadata exposed in the package, like framework, topic, development status, and so on.

大多数时候,您想直接在PyPI网站上搜索软件包。 PyPI提供了针对其索引的搜索功能,并提供了一种通过包中公开的元数据(例如框架,主题,开发状态等)过滤结果的方式。

A search for the same terms in PyPI yields a lot of results, but you can filter them by different categories. For example, you can expand the Intended Audience and select Developers since you want a library that helps you with developing your application. Also, you probably want a package that is stable and production-ready. You can expand the Development Status category and select Production/Stable:

在PyPI中搜索相同的术语会产生很多结果,但是您可以按不同类别对其进行过滤。 例如,您可以扩展目标受众并选择开发人员,因为您需要一个可帮助您开发应用程序的库。 另外,您可能需要一种稳定且可立即投入生产的包装。 您可以展开“开发状态”类别,然后选择“生产/稳定”:

pythonista_什么是点子? 新Pythonista指南_第1张图片

You can apply additional filters and tweak the search terms until you find the package that you are looking for.

您可以应用其他过滤器并调整搜索条件,直到找到所需的软件包。

The results provide a link to the package page, which contains more information and hopefully some documentation. Let’s take a look at the information for requests-oauth2:

结果提供了指向软件包页面的链接,该页面包含更多信息以及希望的一些文档。 让我们看一下requests-oauth2的信息:

pythonista_什么是点子? 新Pythonista指南_第2张图片

The project page provides more information, and it seems to have a link to the project homepage. The link takes you to the project repository on GitHub. There, you can see some more information about the project and some usage examples.

该项目页面提供了更多信息,并且似乎有一个指向项目主页的链接。 该链接将您带到GitHub上的项目存储库 。 在这里,您可以看到有关该项目的更多信息以及一些用法示例。

Finding the original source code repository can be an invaluable resource. There, you can find some hints about the status of the project by looking at the date of the latest commits, number of pull request and open issues, and so forth.

查找原始的源代码存储库可能是宝贵的资源。 在这里,可以通过查看最新提交的日期,拉取请求的数量和未解决的问题等找到有关项目状态的一些提示。

Another option to find a package is to Google it. Widely used Python libraries will show up at the top of google searches, and you should be able to find a link to the package in PyPI or its source code repository.

查找软件包的另一种选择是Google。 广泛使用的Python库将显示在Google搜索的顶部,您应该能够在PyPI或其源代码存储库中找到该包的链接。

Finding the right package may take some time and research, but it will also speed up your development process once you find it.

找到合适的程序包可能需要花费一些时间和研究,但是一旦找到,它也将加快您的开发过程。

卸载软件包 (Uninstalling Packages)

Once in a while, you will have to uninstall a package. You either found a better library to replace it, or it is something you don’t really need. Uninstalling packages can be a bit tricky.

有时,您将必须卸载软件包。 您或者找到了一个更好的库来替换它,或者它并不是您真正需要的。 卸载软件包可能有些棘手。

Notice that, when you installed requests, pip installed other dependencies too. The more packages you install, the bigger the chances that multiple packages depend on the same dependency. This is where the show command in pip comes in handy.

注意,当您安装requestspip安装了其他依赖项。 您安装的软件包越多,多个软件包依赖于相同依赖性的机会就越大。 这是pip中的show命令派上用场的地方。

Before you uninstall a package, make sure you run the show command for that package:

卸载软件包之前,请确保您对该软件包运行show命令:

Notice the last two fields Requires and Required-by. The show command tells us that requests requires urllib3, certifi, chardet, and idna. You probably want to uninstall those two. You can also see that requests is not required by any other package, so it is safe to uninstall it.

注意最后两个字段RequiresRequired-by show命令告诉我们, requests需要urllib3certifichardetidna 您可能要卸载这两个。 您还可以看到其他任何软件包都不需要requests ,因此可以安全地将其卸载。

You should run the show command against all of the requests dependencies to make sure that no other libraries also depend on them. Once you understand the dependency order of the packages you want to uninstall, you can remove them using the uninstall command:

您应该对所有requests依赖项运行show命令,以确保没有其他库也依赖它们。 了解要卸载的软件包的依赖关系顺序后,可以使用uninstall命令将其删除:

 $ pip uninstall certifi

$ pip uninstall certifi

Uninstalling certifi-2018.11.29:
Uninstalling certifi-2018.11.29:
  Would remove:
  Would remove:
    py37libsite-packagescertifi-2018.11.29.dist-info*
    py37libsite-packagescertifi-2018.11.29.dist-info*
    py37libsite-packagescertifi*
    py37libsite-packagescertifi*
Proceed (y/n)? y
Proceed (y/n)? y
  Successfully uninstalled certifi-2018.11.29
  Successfully uninstalled certifi-2018.11.29

Uninstalling a package shows you the files that will be removed and will ask for confirmation. If you are sure you want to remove the package because you’ve checked its dependencies and know that nothing else is using it, you can pass a -y switch to suppress the file list and confirmation:

卸载软件包会显示将被删除的文件,并要求您确认。 如果确定已经检查了软件包的依赖关系,并且确定自己没有其他任何正在使用的软件包,那么可以通过-y开关来禁止显示文件列表和确认:

You can specify all the packages you want to uninstall in a single call: pip uninstall -y urllib3 chardet idna requests.

您可以在一个调用中指定要卸载的所有软件包: pip uninstall -y urllib3 chardet idna requests

You can also uninstall all the packages listed in a requirements file by providing the -r option. The command will ask confirmation for each individual package, but you can suppress it, if you know what you’re doing, with the -y switch:

您还可以通过提供-r 选项来卸载需求文件中列出的所有软件包。 该命令将询问每个软件包的确认信息,但是如果您知道自己在做什么,则可以使用-y开关来取消确认:

 $ pip uninstall -r requirements.txt -y

$ pip uninstall -r requirements.txt -y

Uninstalling certifi-2018.11.29:
Uninstalling certifi-2018.11.29:
  Successfully uninstalled certifi-2018.11.29
  Successfully uninstalled certifi-2018.11.29
Uninstalling chardet-3.0.4:
Uninstalling chardet-3.0.4:
  Successfully uninstalled chardet-3.0.4
  Successfully uninstalled chardet-3.0.4
Uninstalling idna-2.8:
Uninstalling idna-2.8:
  Successfully uninstalled idna-2.8
  Successfully uninstalled idna-2.8
Uninstalling requests-2.21.0:
Uninstalling requests-2.21.0:
  Successfully uninstalled requests-2.21.0
  Successfully uninstalled requests-2.21.0
Uninstalling urllib3-1.24.1:
Uninstalling urllib3-1.24.1:
  Successfully uninstalled urllib3-1.24.1
  Successfully uninstalled urllib3-1.24.1

Remember to always check the dependencies of packages you want to uninstall. You probably want to uninstall all its dependencies, but uninstalling a package that is being used by others will break your application.

切记始终检查要卸载的软件包的依赖性。 您可能希望卸载其所有依赖项,但是卸载其他人正在使用的软件包将破坏您的应用程序。

pip替代品 (Alternatives to pip)

pip is an essential tool for all Pythonistas, and it is used by many applications and projects for package management. This tutorial has helped you with the basics, but the Python community is very active in providing great tools and libraries for other developers to use. These include other alternatives to pip that try to simplify and improve package management.

pip是所有Pythonista使用者必不可少的工具,许多应用程序和项目都使用pip进行软件包管理。 本教程为您提供了基础知识,但是Python社区非常活跃,为其他开发人员提供了出色的工具和库。 这些包括pip其他替代方法,这些替代方法试图简化和改善程序包管理。

In this section, you’ll learn about other package management tools available for Python.

在本节中,您将了解其他可用于Python的软件包管理工具。

康达做到了 (Conda Does It All)

Conda is a package, dependency, and environment manager for many languages including Python. In fact, its origin comes from Anaconda, which started as a data science package for Python.

Conda是许多语言(包括Python)的软件包,依赖项和环境管理器。 实际上,它的起源是Anaconda ,它最初是为Python 编写的数据科学软件包。

Conda is widely used for data science and machine learning applications, and uses its own index to host compatible packages.

Conda广泛用于数据科学和机器学习应用程序,并使用其自己的索引托管兼容的程序包。

Conda not only allows you to manage package dependencies, but it also manages virtual environments for your applications, installs compatible Python distributions, and packages your application for deployment to production.

Conda不仅允许您管理程序包依赖性,而且还可以管理应用程序的虚拟环境,安装兼容的Python发行版以及打包应用程序以部署到生产环境。

Setting Up Python for Machine Learning on Windows is a great introduction to Conda that explores package and environment management. The only Windows-specific information is around installation, so it’s still relevant if you use a different OS platform.

在Windows上为Python设置Python进行机器学习是Conda的精彩介绍,它探讨了软件包和环境管理。 唯一的Windows特定信息是有关安装的,因此,如果您使用其他OS平台,则该信息仍然有用。

Pipenv (Pipenv)

Pipenv is another package management tool that “aims to bring the best of all packaging worlds” to Python. It’s gaining a lot of traction among the Python community because it merges virtual environment and package management in a single tool.

Pipenv是另一种软件包管理工具,“旨在将所有包装领域的精华带给Python”。 它在Python社区中吸引了很多关注,因为它将虚拟环境和程序包管理合并在一个工具中。

It also solves some of the most common hiccups you will run into when manually managing dependencies through pip, like versions of packages, separating development and production dependencies, and locking versions for production.

它还解决了通过pip手动管理依赖项时遇到的一些最常见的问题,例如包的版本,分离开发和生产的依赖项以及锁定生产的版本。

Pipenv: A Guide to the New Python Packaging Tool is a great start to learn about Pipenv and its approach to package management. Even though the article is tagged as intermediate, the author does a great job of guiding the reader that the article is accessible to anyone starting with Python.

Pipenv:新Python打包工具指南是学习Pipenv及其软件包管理方法的一个很好的开端。 即使将文章标记为intermediate文章,作者也可以很好地指导读者使用Python开头的任何人都可以访问该文章。

诗歌 (Poetry)

Poetry is another pip alternative that is gaining a lot of traction. Like Pipenv, it simplifies package version management and separates development vs production dependencies, and it works by isolating those dependencies into a virtual environment.

诗是另一种pip选择。 与Pipenv一样,它简化了程序包版本管理,将开发和生产依赖关系分开,并且通过将这些依赖关系隔离到虚拟环境中来工作。

If you are coming from JavaScript and npm, then Poetry will look very familiar. It goes beyond package management, helping you build distributions for your applications and libraries and deploying them to PyPI. How to Publish an Open-Source Python Package to PyPI has a good introduction to Poetry and can help you get started.

如果您来自JavaScript和npm ,那么诗歌将看起来非常熟悉。 它超越了软件包管理,可帮助您为应用程序和库构建发行版并将其部署到PyPI。 如何将开源Python程序包发布到PyPI, 对Poetry进行了很好的介绍 ,可以帮助您入门。

结论:什么是pip (Conclusion: What Is pip?)

This tutorial answered the question, what is pip? You’ve seen that pip is a package manager for Python, used by many projects to manage dependencies. It’s included with the Python installer, which makes it an essential tool for all Pythonistas to know how to use.

本教程回答了这个问题,什么是点子? 您已经看到pip是Python的软件包管理器,许多项目都使用pip来管理依赖项。 它包含在Python安装程序中,这使它成为所有Pythonista用户知道如何使用的必备工具。

Python provides an extensive standard library suitable for developing all sorts of applications, but the active Python community provides an even larger set of tools and libraries that speed up Python application development.

Python提供了广泛的标准库,适合开发各种应用程序,但是活跃的Python社区提供了更多的工具和库,可加快Python应用程序的开发速度。

These tools and libraries are published to the Python Package Index (PyPI), and pip allows developers to install them in their application environments.

这些工具和库已发布到Python软件包索引 (PyPI),并且pip允许开发人员将其安装在其应用程序环境中。

In this tutorial, you’ve learned about:

在本教程中,您了解了:

  • Installing new packages using pip in the command line and with requirement files
  • Managing dependencies, separating development and production requirements, and creating a locked requirements file
  • Finding packages through pip and PyPI
  • Evaluating package dependencies before uninstalling a package and how pip uninstalls packages
  • 在命令行中使用pip和要求文件安装新软件包
  • 管理依赖关系,分离开发和生产需求以及创建锁定的需求文件
  • 通过pip和PyPI查找软件包
  • 在卸载软件包之前评估软件包的依赖性以及pip如何卸载软件包

In addition, you’ve learned about the importance of keeping dependencies up to date and alternatives to pip that can help you manage those dependencies.

此外,您还了解了保持依赖关系最新的重要性以及可以帮助您管理这些依赖关系的pip替代方法。

Feel free to reach out in the comments section below with any questions you might have, and you can always get more information at the pip documentation page.

如有任何疑问,请随时在下面的评论部分中提出,您随时可以在pip文档页面上获取更多信息。

翻译自: https://www.pybloggers.com/2019/04/what-is-pip-a-guide-for-new-pythonistas/

pythonista

你可能感兴趣的:(python,人工智能,java,大数据,编程语言)