有没有办法在安装时自动将依赖项添加到 requirements.txt?

Is there a way to automatically add dependencies to requirements.txt as they are installed?

类似于 Node.js 自动将依赖项添加到 package-lock.json 的方式,有没有一种方法可以自动将要求添加到 Python 的 requirements.txt 文件中?

如果您使用的是 Linux,您可以像这样创建一个别名:

alias req='pip3 freeze > ~/requerments.txt'

然后当你想安装新包时使用这个命令:

pip3 install <package> | req

由于您具体提到了 Node.js,因此最接近您要查找的 Python 项目可能是 Pipenv

简介 from the Pipenv documentation:

Pipenv is a dependency manager for Python projects. If you're familiar with Node.js's npm or Ruby’s bundler, it is similar in spirit to those tools. While pip can install Python packages, Pipenv is recommended as it’s a higher-level tool that simplifies dependency management for common use cases.

正如 many stars on GitHub 证明的那样,它在开发人员中非常受欢迎。

或者,您可以使用“虚拟环境”,在其中只安装项目需要的外部依赖项。您可以使用 venv module from the standard library or the Virtualenv package from PyPI, which offers certain additional features (that you may or may not need). With either of those, you can then use Python's (standard) package manager Pip to update the requirements file:

pip freeze >requirements.txt

可以说这是“半自动”方式。就个人而言,我更喜欢手动执行此操作。这是因为在典型的开发环境(“虚拟”或非虚拟)中,您还安装了仅用于开发任务所需的包,例如 运行 测试或构建文档。它们不需要与您的软件包一起安装在最终用户机器上,因此不应该在 requirements.txt 中。 Flit and Poetry manage these "extra dependencies" separately, as does Pip.

等流行的打包工具

我想,to-requirements.txt是你需要的:

pip install to-requirements.txt
requirements-txt setup

之后安装的软件包将附加到 requirements.txt。并且卸载的包将被删除。 如果您将它安装在 system-wide Python 解释器上,它可能需要 root 访问权限。如果失败,请添加sudo