Loading...
Loading...
Python single-file script development using uv and PEP 723 inline metadata. Prevents invalid patterns like [tool.uv.metadata]. Use when creating standalone Python utilities, converting scripts to uv format, managing script dependencies, implementing script testing, or establishing team standards for script development.
npx skill4agent add basher83/lunar-claude python-uv-scripts#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "httpx>=0.27.0",
# "rich>=13.0.0",
# ]
# ///
import httpx
from rich import print
response = httpx.get("https://api.github.com")
print(f"[green]Status: {response.status_code}[/green]")chmod +x script.py
./script.py # uv automatically installs dependencies# Add inline metadata to existing script
./tools/convert_to_uv.py existing_script.py
# Validate PEP 723 metadata
./tools/validate_script.py script.py# /// script
# requires-python = ">=3.11"
# dependencies = [
# "package>=1.0.0",
# ]
# ///requirements.txt#!/usr/bin/env -S uv run --script
# /// script
# dependencies = ["httpx"]
# ///uv run script.py # Uses pyproject.toml#!/usr/bin/env -S uv run
# Standard library only# /// script
# requires-python = ">=3.11"
# [tool.uv.metadata] # ❌ THIS DOES NOT WORK
# purpose = "testing"
# ///error: TOML parse error at line 3, column 7
unknown field `metadata`[tool.uv.metadata]# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""
Purpose: Testing automation
Team: DevOps
Author: team@example.com
"""tool.uv# /// script
# requires-python = ">=3.11"
# dependencies = []
# [tool.uv]
# exclude-newer = "2025-01-01T00:00:00Z" # For reproducibility
# ///#!/usr/bin/env python3
import subprocess
# Manual dependency installation required#!/usr/bin/env -S uv run --script --quiet
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "rich>=13.0.0",
# "typer>=0.9.0",
# ]
# ///
"""
Purpose: Cluster health monitoring
Team: Infrastructure
"""
import typer
from rich.console import Console
from rich.table import Tablepyproject.toml# /// script
# requires-python = ">=3.11"
# dependencies = [
# "httpx>=0.27.0", # Minimum version for compatibility
# "rich>=13.0.0", # Known good version
# "ansible>=11.1.0", # Match project requirements
# ]
# ///>=X.Y.Z~=X.Y.Z==X.Y.Zcheck_cluster_health.py # ✅ Descriptive, snake_case
validate_template.py # ✅ Action-oriented
cluster.py # ❌ Too generic#!/usr/bin/env -S uv run --script --quiet
# --quiet suppresses uv's own output#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""
Check Proxmox cluster health
Purpose: cluster-monitoring
Team: infrastructure
Author: devops@spaceships.work
Usage:
python check_cluster_health.py [--node NODE] [--json]
Examples:
python check_cluster_health.py --node foxtrot
python check_cluster_health.py --json
"""import sys
import subprocess
def run_command(cmd: str) -> str:
"""Execute command with proper error handling"""
try:
result = subprocess.run(
cmd.split(),
capture_output=True,
text=True,
check=True
)
return result.stdout
except subprocess.CalledProcessError as e:
print(f"Error: Command failed: {cmd}", file=sys.stderr)
print(f" {e.stderr}", file=sys.stderr)
sys.exit(1)
except FileNotFoundError:
print(f"Error: Command not found: {cmd.split()[0]}", file=sys.stderr)
sys.exit(1)#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
def validate_ip(ip: str) -> bool:
"""Validate IP address format"""
import re
pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
return bool(re.match(pattern, ip))
# Inline tests
if __name__ == "__main__":
import sys
# Run tests if --test flag provided
if len(sys.argv) > 1 and sys.argv[1] == "--test":
assert validate_ip("192.168.1.1") == True
assert validate_ip("256.1.1.1") == False
print("All tests passed!")
sys.exit(0)
# Normal execution
print(validate_ip("192.168.3.5"))# This should be a uv project, not a script:
# - 15+ dependencies
# - Database models
# - API routes
# - Background workers
# - Configuration management
# - Multiple environmentsname: Run Health Checks
on:
schedule:
- cron: '0 */6 * * *' # Every 6 hours
jobs:
health-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v3
- name: Check cluster health
run: |
uv run --script tools/check_cluster_health.py --json
env:
PROXMOX_TOKEN: ${{ secrets.PROXMOX_TOKEN }}cluster-health:
image: ghcr.io/astral-sh/uv:python3.11-bookworm-slim
script:
- uv run --script tools/check_cluster_health.py
only:
- schedules# Validate PEP 723 metadata
./tools/validate_script.py script.py
# Output:
# ✓ Valid PEP 723 metadata
# ✓ Python version specified
# ✓ Dependencies properly formatted# Convert requirements.txt-based script to uv
./tools/convert_to_uv.py old_script.py
# Creates:
# - old_script_uv.py with inline dependencies
# - Preserves original scriptNote: See Common Patterns section above for quick access to these guides.
# Standard script execution
#!/usr/bin/env -S uv run --script
# Quiet mode (suppress uv output)
#!/usr/bin/env -S uv run --script --quiet
# With Python version
#!/usr/bin/env -S uv run --script --python 3.11# CLI applications
"typer>=0.9.0" # Modern CLI framework
"click>=8.0.0" # Alternative CLI framework
"rich>=13.0.0" # Rich text and formatting
# API clients
"httpx>=0.27.0" # Modern async HTTP client
"requests>=2.31.0" # Traditional HTTP client
# Data processing
"polars>=0.20.0" # Fast dataframe library
"pandas>=2.0.0" # Traditional dataframe library
# Infrastructure
"ansible>=11.1.0" # Automation (from this repo)
"infisical-python>=2.3.3" # Secrets (from this repo)
# System automation
"psutil>=5.9.0" # System monitoring#!/usr/bin/env -S uv run --script --quiet
# /// script
# requires-python = ">=3.11"
# dependencies = [
# # Add dependencies here
# ]
# ///
"""
One-line description
Purpose: describe-purpose
Team: team-name
Author: email@example.com
Usage:
python script.py [OPTIONS]
Examples:
python script.py --help
"""requires-python = ">=3.11">=X.Y.Z--quiet--test