Managing dependencies is critical in DevOps. You never want to install packages globally on a server or your local machine, as it can lead to version conflicts.
1. Virtual Environments (venv)
Python includes a built-in module called venv to create isolated environments.
Create and Activate
Action:
# Create the environment
python3 -m venv venv
# Activate it (Linux/macOS)
source venv/bin/activateResult:
Your terminal prompt will change to show (venv), indicating you are now working inside the isolated environment.
2. Managing Packages with pip
pip is the standard package manager for Python.
Install a Package
Action:
pip install requestsResult:
Collecting requests
Downloading requests-2.31.0-py3-none-any.whl (62 kB)
Installing collected packages: requests
Successfully installed requests-2.31.0Freezing Dependencies
DevOps best practice: Always lock your versions.
Action:
pip freeze > requirements.txt
cat requirements.txtResult:
certifi==2023.7.22
charset-normalizer==3.2.0
idna==3.4
requests==2.31.0
urllib3==2.0.43. Modern Tool: Poetry
While pip is great, Poetry is the modern industry standard for dependency management and packaging. It handles virtual environments automatically and uses pyproject.toml.
Initialize a Project
Action:
poetry initResult:
This interactive command will guide you through creating a pyproject.toml file, which is more robust than requirements.txt.
4. DevOps Use Case: Docker Containers
When building Docker images, you should always use a requirements.txt or pyproject.toml to ensure your production environment exactly matches your development environment.
Dockerfile snippet:
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txtSummary
- Always use a virtual environment.
- Use
pip freezeto capture specific versions. - Consider Poetry for complex projects.
- Never install packages as root/sudo unless absolutely necessary.