安装新软件包时如何自动更新需求文件?

Ana*_*ram 12 pip requirements.txt virtual-environment

通过跟踪虚拟环境的需求pip freeze非常简单。

pip freeze > requirements.txt
Run Code Online (Sandbox Code Playgroud)

然而,目前,每当新包添加到venv,都需要手动将其添加到需求文件中。为此,我通常只是再次运行 freeze 命令并将其通过管道传输到需求文件中,但有时我忘记运行此命令,这可能会很麻烦,尤其是在跨不同位置的存储库中,每当我必须记住需要哪些包时安装!

每当在虚拟环境中安装新软件包时,是否有任何方法可以自动更新文件 requirements.txt 以包含这个新软件包?

Gin*_*pin 11

当仅使用 plain 时pip,目前无法使其自动生成或更新requirements.txt 文件。它仍然主要是一个手动过程pip freeze > requirements.txt(请参阅相关的如何创建requirements.txt以了解其他选项)。

如果目的是确保正确跟踪或注册已安装的软件包(即在存储库的版本控制中进行跟踪),那么您将必须使用“包装”功能的其他工具。pip

你有两个选择。

选项 1:使用包管理器

有许多 Python 包管理器将“安装包”与“在某处记录已安装的包”结合起来。

  • 管彭夫
    • 它会自动为您的项目创建和管理 virtualenv,并在您Pipfile安装/卸载软件包时添加/删除软件包。它还会生成非常重要的Pipfile.lock,用于生成确定性构建。
    • 工作流程(请参阅Pipenv 工作流程示例
      $ pipenv install some-package
      
      $ cat Pipfile
      ...
      [packages]
      some-package = "*"
      
      # Commit modified Pipfile and Pipfile.lock
      $ git add Pipfile*
      
      # On some other copy of the repo, install stuff from Pipfile
      $ pipenv install
      
      Run Code Online (Sandbox Code Playgroud)
  • 诗歌
    • 诗歌是一个处理依赖安装以及Python包的构建和打包的工具。它只需要一个文件来完成所有这些工作:新的、标准化的。pyproject.toml换句话说,诗歌用来pyproject.toml替换setup.py、、、和新添加的requirements.txtsetup.cfgMANIFEST.inPipfile.*
    • 工作流程(参见基本用法
      $ poetry add requests
      
      $ cat pyproject.toml
      ...
      [tool.poetry.dependencies]
      requests = "*"
      
      # Commit modified pyproject.toml
      $ git add pyproject.toml
      
      # On some other copy of the repo, install stuff from Pipfile
      $ poetry install
      
      Run Code Online (Sandbox Code Playgroud)

选项 2:git 预提交挂钩

此解决方案不会在“安装包期间”发生,但如果目的是确保跟踪的“requirements.txt”与虚拟环境同步,那么您可以添加一个git 预提交挂钩

  1. 生成单独的requirements_check.txt文件
  2. 将requirements_check.txt 与您的requirements.txt 进行比较
  3. 如果存在差异则中止您的提交

例子.git/hooks/pre-commit

#!/usr/local/bin/bash

pip freeze > requirements_check.txt
cmp --silent requirements_check.txt requirements.txt

if [ $? -gt 0 ]; 
then
  echo "There are packages in the env not in requirements.txt"
  echo "Aborting commit"
  rm requirements_check.txt
  exit 1
fi

rm requirements_check.txt
exit 0
Run Code Online (Sandbox Code Playgroud)

输出:

$ git status
...
nothing to commit, working tree clean

$ pip install pydantic

$ git add .
$ git commit
The output of pip freeze is different from requirements.txt
Aborting commit

$ pip freeze > requirements.txt
$ git add .
$ git commit -m "Update requirements.txt"
[master 313b685] Update requirements.txt
 1 file changed, 1 insertion(+)
Run Code Online (Sandbox Code Playgroud)