G
GuideDevOps
Lesson 3 of 15

Virtual Environments & Packages

Part of the Python for DevOps tutorial series.

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/activate

Result: 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 requests

Result:

Collecting requests
  Downloading requests-2.31.0-py3-none-any.whl (62 kB)
Installing collected packages: requests
Successfully installed requests-2.31.0

Freezing Dependencies

DevOps best practice: Always lock your versions.

Action:

pip freeze > requirements.txt
cat requirements.txt

Result:

certifi==2023.7.22
charset-normalizer==3.2.0
idna==3.4
requests==2.31.0
urllib3==2.0.4

3. 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 init

Result: 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.txt

Summary

  • Always use a virtual environment.
  • Use pip freeze to capture specific versions.
  • Consider Poetry for complex projects.
  • Never install packages as root/sudo unless absolutely necessary.