在 Python 中创建 requirements.txt

Vaibhav Vaibhav 2023年1月30日 2022年5月17日
  1. 使用 pip 软件包安装程序创建 requirements.txt
  2. 使用 pip 包安装程序从 requirements.txt 安装依赖项
在 Python 中创建 requirements.txt

在开发 Python 应用程序时,我们必须使用一堆模块来实现各种功能。应用程序使用的模块数量可能很多。通常,在开发如此庞大的应用程序甚至较小的应用程序时,建议创建特定于项目的虚拟环境,因为它可以让我们安装我们想要的任何版本,而不会装满全局包空间。

如果我们的朋友、家人或同事希望在他们的系统上使用开发人员,他们也需要在他们的一端安装代码和依赖项。由于依赖项安装在虚拟环境中,因此共享整个虚拟环境没有意义,因为文件夹大小会很大,并且它们可能会因完整性问题而面临错误。

在这种情况下,开发人员将 requirements.txt 文件添加到包含虚拟环境中安装的所有依赖项列表和所使用版本的详细信息的项目中。这样,借款人或最终用户只需创建一个虚拟环境并安装依赖项即可使用该应用程序。

本文将指导我们创建 requirements.txt 文件并从 requirements.txt 文件安装依赖项。

使用 pip 软件包安装程序创建 requirements.txt

要生成 requirements.txt 文件,我们可以从命令行使用 pip 包安装程序或包管理系统。相同的请参考以下命令。

pip freeze > requirements.txt
pip3 freeze > requirements.txt

如果你使用的是 conda 包管理器,而不是 pip,则可以使用以下命令生成 requirements.txt 文件。

conda list -e > requirements.txt

使用 pip 包安装程序从 requirements.txt 安装依赖项

一旦我们生成了一个 requirements.txt 文件,我们就可以使用这个文件来安装其中提到的所有依赖项。相同的请参考以下命令。

pip install -r requirements.txt

通常,建议在启动任何新项目和安装任何依赖项之前创建一个虚拟环境。这可确保你不会用随机和不常见的包弄乱全局包空间。相同的工作流程如下。

  1. 创建虚拟环境。
  2. 激活虚拟环境。
  3. 安装依赖项。

相同的请参考以下命令。

virtualenv environment # Create a virtual environment
environment\Scripts\activate # Activate the virtual environment
pip install -r requirements.txt # Install the dependencies
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub

相关文章 - Python Installation