【问题标题】:pip's requirements.txt best practicepip 的 requirements.txt 最佳实践
【发布时间】:2020-08-15 14:06:24
【问题描述】:

我正在尝试为某人生成requirements.txt 来复制我的环境。如您所知,标准方式是

pip freeze > requirements.txt

我注意到这将列出所有包,包括已安装包的依赖项,这使得这个列表不必要的庞大。然后我浏览了一下,发现pip-chill 允许我们只列出requirements.txt 中已安装的包。

现在,据我了解,当有人尝试使用pip install -r requirements.txt 复制环境时,这将自动安装已安装软件包的依赖项。

如果这是真的,这意味着使用pip-chill 而不是pip 来生成requirements.txt 是安全的。我的问题是,是否还有其他使用 pip-chill 忽略已安装软件包的依赖项的风险,而我在这里缺少这些风险?

【问题讨论】:

  • 我不知道 pip chill,但是您必须小心与所需版本不匹配的依赖项的依赖项。例如。您使用 numpy 1.5 和 pandas 1.0(并且该版本的 pandas 要求使用 numpy 1.4)
  • 冻结所有包版本的目的是让你知道你将使用已知的好版本运行。否则可能会出现版本不兼容的错误。
  • @deceze 好吧,如果您安装了特定版本的软件包,它也会知道该版本的良好依赖项版本(根据该版本中该软件包的要求),对吗?所以我假设不需要记录依赖版本?
  • 直到依赖发布了一个新的破坏版本,它破坏了包,直到包发布了一个对其依赖更严格的新版本。这并非闻所未闻。
  • 您可以使用您的直接依赖项设置和维护一个setup.py 文件,以及使用您已知的良好冻结依赖项的requirements.txt 文件。基本上每个主要的依赖管理器都是这样做的,一个直接列表和一个“锁定”文件。

标签: pip requirements.txt


【解决方案1】:

我相信在构建你的 requirements.txt 时,使用 pip-tools 中的 pip-compile 是一种很好的做法。这将确保构建是可预测和确定的。

pip-compile 命令可让您从您的依赖项编译requirements.txt 文件,在setup.pyrequirements.in 中指定

这是我构建你的 requirements.txt 的推荐步骤(如果使用 requirements.in):

  1. 创建一个虚拟环境并在那里安装 pip-tools
$ source /path/to/venv/bin/activate
(venv)$ python -m pip install pip-tools
  1. 在您的 requirements.in 文件中指定您的应用程序/项目的直接依赖项:
# requirements.in
requests
boto3==1.16.51
  1. 使用 pip-compile 生成 requirements.txt
$ pip-compile --output-file=- > requirements.txt

您的 requirements.txt 文件将包含:

#
# This file is autogenerated by pip-compile
# To update, run:
#
#    pip-compile --output-file=-
#
boto3==1.16.51
    # via -r requirements.in
botocore==1.19.51
    # via
    #   boto3
    #   s3transfer
certifi==2020.12.5
    # via requests
chardet==4.0.0
    # via requests
idna==2.10
    # via requests
jmespath==0.10.0
    # via
    #   boto3
    #   botocore
python-dateutil==2.8.1
    # via botocore
requests==2.25.1
    # via -r requirements.in
s3transfer==0.3.3
    # via boto3
six==1.15.0
    # via python-dateutil
urllib3==1.26.2
    # via
    #   botocore
    #   requests

您的应用程序应该始终使用由此生成的requirements.txt 安装的依赖项。如果您必须更新依赖项,您只需更新requirements.in 文件并重做pip-compile。我相信这是一种比我看到一些人这样做的pip freeze > requirements.txt 更好的方法。

我想使用它的主要优点是您可以在单独的requirement.in 文件中跟踪项目的实际直接依赖关系

我发现这与使用 package.json (requirements.in) 和 package-lock.json (requirements.txt) 在节点应用项目中管理节点模块/依赖项的方式非常相似。

【讨论】:

    【解决方案2】:

    从我的角度来看,requirements.txt 文件应该列出所有依赖项、直接依赖项以及它们的依赖项(间接、瞬态)。如果由于某种原因,只需要直接依赖项,那么有一些工具可以帮助解决这个问题,粗略地看,pip-chill 似乎不够用,因为它实际上并没有查看代码来找出什么包直接导入。也许更好地查看诸如pipreqspigar 之类的项目,它们似乎更准确地确定了实际的直接依赖项是什么(基于代码中的导入)。

    但归根结底,您应该手动整理此类列表。在编写代码时,您要仔细选择要导入的包,同样注意,您应该整理包含这些包的项目(及其版本)的列表。工具可以提供帮助,但开发人员知道得更清楚。

    【讨论】:

      猜你喜欢
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 2014-10-08
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多