pip install 中的方括号是什么意思?

What do square brackets mean in pip install?

我看到越来越多这样的命令:

$ pip install "splinter[django]"

这些方括号有什么作用?

您使用的语法是:

pip install "project[extra]"

在你的例子中,你是 installing splinter 包,它增加了对 django 的支持。方括号 ([]) 不是特定语法,只是约定俗成。实际上,您正在安装名为:"splinter[django]".

的包

来自@chetner的解释:

The command pip install splinter django would install two packages named splinter and django. splinter[django], on the other hand, installs a variant of the splinter package which contains support for django. Note that it has nothing to do with the django package itself, but is just a string defined by the splinter package for a particular feature set that gets enabled.

很确定这些是额外的安装工具:

https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies

Sometimes a project has “recommended” dependencies, that are not required for all uses of the project. For example, a project might offer optional PDF output if ReportLab is installed, and reStructuredText support if docutils is installed. These optional features are called “extras” ...

这正是 question 中项目的 setup.py 文件中的列表:

"django": ["Django>=1.7.11;python_version<'3.0'", "Django>=2.0.6;python_version>'3.3'", "lxml>=2.3.6", "cssselect", "six"],

PIP 中的括号 [optional] 表示可选依赖项

以防万一其他开发人员希望在他们自己的 Python 包部署中实现此模式,这里是对 pip 中 brackets [] 的进一步解释。

例如:Apache Airflow

要从 pip 安装 airflow,我们使用此命令:

pip install 'apache-airflow'

您可以安装 可选 airflow 组件:

pip install 'apache-airflow[aws]'
#      [optional] -----------^

当我们搜索 pypi for apache-airflow时注意可选包没有显示:

pip search 'apache-airflow'

apache-airflow (1.10.9)                            - Programmatically author, schedule and monitor data pipelines
pylint-airflow (0.1.0a1)                           - A Pylint plugin to lint Apache Airflow code.
swe-airflow-tools (0.0.3)                          - Tools for Apache Airflow Application
airflow (0.6)                                      - Placeholder for the old Airflow package
...

通过setup.py

实施

您可以在 setup.py script
中看到这是如何完成的 左边在setup.py-extras_require中定义。
右边是这些可选子包的相关安装命令。

也许值得知道这个可选包语法允许多个附加项(在括号内用逗号分隔),如:

python -m pip install SomePackage[PDF,EPUB]  # multiple extras

根据 pip manual

TLDR

方括号包含在 setup.py 中定义的 'extra' 选项的信息,pip 将使用它来安装其他依赖项。

pip install "splinter[django]"

具体来说,上面的行将首先安装 'splinter' 包,然后安装 'splinter' 项目所需的额外依赖项,并使用 [=40] 中指定的 'django' 选项=] 'splinter' 个项目。

说明

pip install "splinter[django]" 

pip install "splinter" "Django>=2.0.6" "lxml>=4.2.4" "cssselect"

从splinter==0.16.0开始,随着python==3.9.2,以上两个命令是等价的。

在干净的虚拟环境下,这两个 pip 安装都会生成以下包。

之所以这两个pip install命令的效果一样,是因为这就是字面上已经运行在后台基于setup.py的splinter包

'[django]' 是 'splinter' 包的 'extra' 选项。 Pip 将查看 splinter 包的 setup.py,并找到需要使用指定的 '[django]' 选项安装的内容。在本例中,就是这 3 个包:["Django>=2.0.6", "lxml>=4.2.4", "cssselect"]