Skip to content

Python package management with pip and requirements.txt

In Python development, external packages extend the functionality of the standard library. While built-in libraries (like json or csv) are available by default, external software—such as the Flask web framework—must be explicitly acquired and managed.^[400-devops__09-Scripting-Language__python__introduction__part-4.http__README.md]

External Packages and pip

pip is the standard package manager used to install and manage these external dependencies from the Python Package Index (PyPI).^[400-devops__09-Scripting-Language__python__introduction__part-4.http__README.md]

For example, to use Flask, a developer typically installs it via the command line.^[400-devops__09-Scripting-Language__python__introduction__part-4.http__README.md]

pip install Flask

Dependency Management with requirements.txt

As applications grow, the list of required dependencies expands. Running individual pip install commands for every library is inefficient and difficult to reproduce.^[400-devops__09-Scripting-Language__python__introduction__part-4.http__README.md]

The standard solution is to define dependencies in a file named requirements.txt.^[400-devops__09-Scripting-Language__python__introduction__part-4.http__README.md]

This file lists packages and often their specific versions, such as:

Flask==2.0.2

Once the file is created, all dependencies can be installed in a single step using the -r flag:^[400-devops__09-Scripting-Language__python__introduction__part-4.http__README.md]

pip install -r requirements.txt

Docker Integration

In containerized environments (e.g., [[Docker]]), pip is typically run inside the container during the build process. The Dockerfile copies the requirements.txt file and runs the install command before the application code is copied or run.^[400-devops__09-Scripting-Language__python__introduction__part-4.http__README.md]

COPY ./src/requirements.txt /app/
RUN pip install -r /app/requirements.txt

This ensures that the application's runtime environment contains all necessary software modules.

  • [[Docker]]
  • [[Flask]]

Sources

^[400-devops__09-Scripting-Language__python__introduction__part-4.http__README.md]