| name | python-venv-manager |
| description | Python virtual environment management, dependency handling, and project setup automation. |
Python Virtual Environment Manager Skill
Python virtual environment management, dependency handling, and project setup automation.
Instructions
You are a Python environment and dependency expert. When invoked:
-
Virtual Environment Management:
- Create and configure virtual environments
- Manage Python versions with pyenv
- Set up isolated development environments
- Handle multiple Python versions per project
- Configure environment activation scripts
-
Dependency Management:
- Generate and manage requirements.txt
- Use modern tools (pip-tools, poetry, pipenv)
- Lock dependencies with hashes
- Handle dev vs production dependencies
- Resolve dependency conflicts
-
Project Setup:
- Initialize new Python projects
- Configure project structure
- Set up testing frameworks
- Configure linting and formatting
- Create reproducible environments
-
Troubleshooting:
- Fix import errors
- Resolve version conflicts
- Debug installation issues
- Handle platform-specific dependencies
- Clean corrupted environments
-
Best Practices: Provide guidance on Python packaging, versioning, and environment isolation
Virtual Environment Tools Comparison
venv (Built-in)
python3 -m venv venv
source venv/bin/activate
venv\Scripts\activate
deactivate
pip install -r requirements.txt
virtualenv (Enhanced)
pip install virtualenv
virtualenv -p python3.11 venv
virtualenv --system-site-packages venv
Poetry (Modern, Recommended)
curl -sSL https://install.python-poetry.org | python3 -
poetry new my-project
poetry init
poetry add requests
poetry add --group dev pytest
poetry install
poetry run python script.py
poetry run pytest
poetry shell
poetry update
poetry show --tree
Pipenv
pip install pipenv
pipenv install requests
pipenv install --dev pytest
pipenv shell
pipenv run python script.py
pipenv requirements > requirements.txt
pyenv (Python Version Manager)
curl https://pyenv.run | bash
pyenv install 3.11.5
pyenv install 3.12.0
pyenv install --list
pyenv global 3.11.5
pyenv local 3.11.5
pyenv versions
pyenv version
Usage Examples
@python-venv-manager
@python-venv-manager --setup-project
@python-venv-manager --create-venv
@python-venv-manager --poetry
@python-venv-manager --fix-dependencies
@python-venv-manager --migrate-to-poetry
Project Setup Workflows
Basic Project with venv
mkdir my-project
cd my-project
python3 -m venv venv
source venv/bin/activate
venv\Scripts\activate
pip install --upgrade pip
pip install requests pytest black flake8
pip freeze > requirements.txt
cat > .gitignore << EOF
venv/
__pycache__/
*.pyc
*.pyo
*.pyd
.Python
*.so
*.egg
*.egg-info/
dist/
build/
.pytest_cache/
.coverage
htmlcov/
.env
.venv
EOF
Modern Project with Poetry
poetry new my-project
cd my-project
poetry add requests httpx pydantic
poetry add --group dev pytest pytest-cov black flake8 mypy
poetry install
cat >> pyproject.toml << EOF
[tool.black]
line-length = 88
target-version = ['py311']
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = "test_*.py"
[tool.mypy]
python_version = "3.11"
warn_return_any = true
warn_unused_configs = true
EOF
Initialize Existing Project
cd existing-project
poetry init
poetry add $(cat requirements.txt)
poetry add --group dev pytest black flake8
poetry install
poetry run python -c "import requests; print(requests.__version__)"
Dependency Management
requirements.txt Best Practices
requests==2.31.0
django==4.2.7
celery==5.3.4
pip-compile --generate-hashes requirements.in
requirements/
├── base.txt
├── development.txt
├── production.txt
└── testing.txt
-r base.txt
pytest==7.4.3
black==23.11.0
flake8==6.1.0
pip install -r requirements/development.txt
Using pip-tools (Recommended)
pip install pip-tools
cat > requirements.in << EOF
django>=4.2,<5.0
requests
celery[redis]
EOF
pip-compile requirements.in
pip-sync requirements.txt
pip-compile --upgrade requirements.in
pip-compile --generate-hashes requirements.in
Poetry Dependency Management
poetry add "django>=4.2,<5.0"
poetry add django@4.2.7
poetry add git+https://github.com/user/repo.git
poetry add --editable ./local-package
poetry add "celery[redis,auth]"
poetry update django
poetry update
poetry show --outdated
poetry remove requests
poetry export -f requirements.txt --output requirements.txt
poetry export --without-hashes -f requirements.txt --output requirements.txt
Development vs Production Dependencies
[tool.poetry.dependencies]
python = "^3.11"
django = "^4.2"
requests = "^2.31"
[tool.poetry.group.dev.dependencies]
pytest = "^7.4"
black = "^23.11"
flake8 = "^6.1"
poetry install --without dev
poetry install --only dev
django>=4.2
requests
-r requirements.in
pytest>=7.4
black>=23.11
flake8>=6.1
pip-compile requirements.in
pip-compile requirements-dev.in
Python Version Management
Using pyenv
curl https://pyenv.run | bash
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
pyenv install 3.11.5
pyenv install 3.12.0
pyenv global 3.11.5
pyenv local 3.11.5
pyenv virtualenv 3.11.5 my-project-env
pyenv activate my-project-env
pyenv deactivate
pyenv virtualenvs
pyenv uninstall my-project-env
Using pyenv with Poetry
pyenv local 3.11.5
poetry init
poetry env use python
poetry env use 3.11
poetry env list
poetry env remove python3.11
poetry env info
Project Structure Best Practices
Small Project
my-project/
├── .gitignore
├── README.md
├── requirements.txt
├── setup.py (optional)
├── my_module.py
└── tests/
├── __init__.py
└── test_my_module.py
Medium Project
my-project/
├── .gitignore
├── README.md
├── pyproject.toml
├── setup.py
├── requirements/
│ ├── base.txt
│ ├── development.txt
│ └── production.txt
├── src/
│ └── my_package/
│ ├── __init__.py
│ ├── core.py
│ ├── utils.py
│ └── models.py
├── tests/
│ ├── __init__.py
│ ├── conftest.py
│ └── test_core.py
└── docs/
└── index.md
Large Project with Poetry
my-project/
├── .gitignore
├── .python-version
├── README.md
├── pyproject.toml
├── poetry.lock
├── src/
│ └── my_package/
│ ├── __init__.py
│ ├── core/
│ │ ├── __init__.py
│ │ └── engine.py
│ ├── api/
│ │ ├── __init__.py
│ │ └── routes.py
│ └── utils/
│ ├── __init__.py
│ └── helpers.py
├── tests/
│ ├── __init__.py
│ ├── conftest.py
│ ├── unit/
│ │ └── test_core.py
│ └── integration/
│ └── test_api.py
├── docs/
│ ├── conf.py
│ └── index.rst
└── scripts/
└── setup_dev.sh
Common Issues & Solutions
Issue: ModuleNotFoundError
which python
pip list | grep package-name
pip install --force-reinstall package-name
python -c "import sys; print('\n'.join(sys.path))"
source venv/bin/activate
pip install -e .
Issue: Dependency Conflicts
pip check
pip install pipdeptree
pipdeptree
poetry add package-name
pip install "package==1.2.3"
pip-compile --resolver=backtracking requirements.in
Issue: Multiple Python Versions Confusion
python --version
which python
python3.11 -m venv venv
pyenv versions
pyenv which python
pyenv local 3.11.5
Issue: Corrupted Virtual Environment
rm -rf venv/
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
poetry env remove python3.11
poetry install
Issue: SSL Certificate Errors
pip install --trusted-host pypi.org --trusted-host pypi.python.org package-name
pip install --upgrade certifi
/Applications/Python\ 3.11/Install\ Certificates.command
Issue: Permission Denied
chown -R $USER:$USER venv/
pip install --user package-name
Environment Variables and Configuration
.env Files
poetry add python-dotenv
cat > .env << EOF
DEBUG=True
SECRET_KEY=your-secret-key
DATABASE_URL=postgresql://user:pass@localhost/db
REDIS_URL=redis://localhost:6379
EOF
from dotenv import load_dotenv
import os
load_dotenv()
DEBUG = os.getenv('DEBUG', 'False') == 'True'
SECRET_KEY = os.getenv('SECRET_KEY')
DATABASE_URL = os.getenv('DATABASE_URL')
Environment-Specific Settings
import os
from pathlib import Path
class Config:
BASE_DIR = Path(__file__).parent
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = False
TESTING = False
class DevelopmentConfig(Config):
DEBUG = True
DATABASE_URL = 'sqlite:///dev.db'
class ProductionConfig(Config):
DATABASE_URL = os.getenv('DATABASE_URL')
class TestingConfig(Config):
TESTING = True
DATABASE_URL = 'sqlite:///test.db'
config = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'testing': TestingConfig,
'default': DevelopmentConfig
}
def get_config():
env = os.getenv('FLASK_ENV', 'default')
return config[env]()
Testing Setup
pytest Configuration
poetry add --group dev pytest pytest-cov pytest-mock
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = "test_*.py"
python_classes = "Test*"
python_functions = "test_*"
addopts = "-v --tb=short --strict-markers"
poetry run pytest
poetry run pytest --cov=src --cov-report=html
poetry run pytest tests/test_core.py::test_function_name
Code Quality Tools
Formatting and Linting
poetry add --group dev black isort flake8 mypy pylint
[tool.black]
line-length = 88
target-version = ['py311']
include = '\.pyi?$'
extend-exclude = '''
/(
# directories
\.eggs
| \.git
| \.venv
| build
| dist
)/
'''
[tool.isort]
profile = "black"
line_length = 88
[tool.mypy]
python_version = "3.11"
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
poetry run black .
poetry run isort .
poetry run flake8 src/
poetry run mypy src/
poetry run pylint src/
Pre-commit Hooks
poetry add --group dev pre-commit
cat > .pre-commit-config.yaml << EOF
repos:
- repo: https://github.com/psf/black
rev: 23.11.0
hooks:
- id: black
language_version: python3.11
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
args: ["--profile", "black"]
- repo: https://github.com/pycqa/flake8
rev: 6.1.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.7.0
hooks:
- id: mypy
additional_dependencies: [types-requests]
EOF
poetry run pre-commit install
poetry run pre-commit run --all-files
Migration Scripts
Migrate from requirements.txt to Poetry
echo "Migrating to Poetry..."
cp requirements.txt requirements.txt.backup
poetry init --no-interaction
cat requirements.txt | grep -v "^#" | grep -v "^$" | while read package; do
pkg_name=$(echo $package | cut -d'=' -f1 | cut -d'>' -f1 | cut -d'<' -f1)
poetry add "$pkg_name"
done
poetry install
echo "Migration complete. Check pyproject.toml"
echo "Original requirements.txt backed up to requirements.txt.backup"
Convert between formats
poetry export -f requirements.txt --output requirements.txt --without-hashes
cat requirements.txt | xargs poetry add
pipenv requirements > requirements.txt
poetry add $(pipenv requirements | sed 's/==/=/g')
Docker Integration
Dockerfile with Virtual Environment
FROM python:3.11-slim
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y \
gcc \
&& rm -rf /var/lib/apt/lists/*
# Copy dependency files
COPY requirements.txt .
# Create virtual environment and install dependencies
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN pip install --no-cache-dir -r requirements.txt
# Copy application
COPY . .
# Run as non-root
RUN useradd -m -u 1001 appuser && \
chown -R appuser:appuser /app
USER appuser
CMD ["python", "app.py"]
Dockerfile with Poetry
FROM python:3.11-slim as builder
WORKDIR /app
# Install Poetry
RUN pip install poetry==1.7.0
# Configure Poetry
ENV POETRY_NO_INTERACTION=1 \
POETRY_VIRTUALENVS_IN_PROJECT=1 \
POETRY_VIRTUALENVS_CREATE=1 \
POETRY_CACHE_DIR=/tmp/poetry_cache
# Copy dependency files
COPY pyproject.toml poetry.lock ./
# Install dependencies
RUN poetry install --without dev --no-root && rm -rf $POETRY_CACHE_DIR
# Runtime stage
FROM python:3.11-slim as runtime
WORKDIR /app
# Copy virtual environment from builder
ENV VIRTUAL_ENV=/app/.venv \
PATH="/app/.venv/bin:$PATH"
COPY --from=builder /app/.venv ${VIRTUAL_ENV}
# Copy application
COPY . .
# Run as non-root
RUN useradd -m -u 1001 appuser && \
chown -R appuser:appuser /app
USER appuser
CMD ["python", "app.py"]
Best Practices Summary
Virtual Environment
- Always use virtual environments (never install globally)
- One virtual environment per project
- Keep venv/ out of version control (.gitignore)
- Document Python version requirements (.python-version)
- Use pyenv for managing multiple Python versions
Dependency Management
- Pin exact versions in production (no ~, ^)
- Use pip-tools or Poetry for dependency resolution
- Separate dev and production dependencies
- Use lock files (poetry.lock, requirements.txt with hashes)
- Regularly update dependencies for security
- Document why specific versions are pinned
Project Structure
- Use src/ layout for packages
- Keep tests separate from source
- Include comprehensive .gitignore
- Add README.md with setup instructions
- Use pyproject.toml for modern projects
Security
- Never commit .env files
- Use python-dotenv for environment variables
- Scan dependencies with pip-audit or safety
- Use hashes in requirements.txt
- Keep dependencies minimal
- Update regularly for security patches
Development Workflow
- Use pre-commit hooks for code quality
- Configure formatters (black, isort)
- Use type hints and mypy
- Write tests with pytest
- Document setup steps in README
Quick Reference Commands
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pip freeze > requirements.txt
poetry new project
poetry init
poetry add package
poetry install
poetry shell
poetry run python script.py
pyenv install 3.11.5
pyenv local 3.11.5
pyenv virtualenv 3.11.5 myenv
pip-compile requirements.in
pip-sync requirements.txt
pip-compile --upgrade
pip list --outdated
pip check
poetry show --outdated
poetry update
Notes
- Prefer Poetry or pip-tools over manual requirements.txt management
- Use pyenv to manage multiple Python versions
- Always activate virtual environment before installing packages
- Keep dependencies documented and up-to-date
- Use lock files for reproducible builds
- Test dependency updates in isolated environment first
- Configure proper .gitignore to exclude virtual environments
- Use type hints and static analysis tools (mypy)
- Set up CI/CD to verify dependency installation
- Regular security audits of dependencies