From aa7fca9f0c4890ad82482275fcbfb47fa0f9dc60 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 20 Oct 2025 19:00:01 +0000 Subject: [PATCH] Add Python examples to devbox-config MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Created python/ directory with example scripts - Added hello_world.py: Simple Hello World with type hints - Added example_utils.py: Comprehensive utilities demonstrating: * Running shell commands from Python * Reading and parsing JSON files * File system operations and directory analysis * Type hints and documentation best practices - Added python/README.md with usage instructions - Updated main README.md with Python examples section All scripts are tested and working with Python 3.13 included in devbox. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- README.md | 17 +++- python/README.md | 74 +++++++++++++++++ python/example_utils.py | 179 ++++++++++++++++++++++++++++++++++++++++ python/hello_world.py | 25 ++++++ 4 files changed, 294 insertions(+), 1 deletion(-) create mode 100644 python/README.md create mode 100755 python/example_utils.py create mode 100755 python/hello_world.py diff --git a/README.md b/README.md index 6153db4..10c788c 100644 --- a/README.md +++ b/README.md @@ -30,12 +30,27 @@ devbox global pull https://devbox.getfleek.dev/none devbox global pull https://github.com/wardnath/devbox-config.git ``` -## cli devcontainer reset and run +## cli devcontainer reset and run ```bash git pull && devcontainer up --workspace-folder . --remove-existing-container && sleep 2 && devcontainer exec --workspace-folder . zsh ``` +## Python Examples + +The `python/` directory contains example Python scripts demonstrating various capabilities: + +* `hello_world.py` - Simple Hello World example with type hints +* `example_utils.py` - Comprehensive utilities showing file operations, JSON parsing, and system commands + +Run examples: +```bash +python python/hello_world.py +python python/example_utils.py +``` + +See [python/README.md](python/README.md) for more details on using Python in this devbox environment. + ## Secrets etc Most of the config here aims to be generally applicable. The secrets in the dotconfig are managed by chezmoi ejson https://www.chezmoi.io/user-guide/password-managers/ejson/ diff --git a/python/README.md b/python/README.md new file mode 100644 index 0000000..82617be --- /dev/null +++ b/python/README.md @@ -0,0 +1,74 @@ +# Python Examples + +This directory contains Python example scripts for the devbox-config environment. + +## Prerequisites + +Python 3.13 is included in the devbox configuration. No additional setup required. + +## Examples + +### 1. Hello World (`hello_world.py`) + +A simple example demonstrating basic Python script structure: + +```bash +python python/hello_world.py +``` + +### 2. Utility Functions (`example_utils.py`) + +A more comprehensive example showing: +- Running shell commands from Python +- Reading and parsing JSON files +- File system operations +- Directory analysis +- Type hints and documentation + +```bash +python python/example_utils.py +``` + +## Running the Examples + +Make the scripts executable (optional): +```bash +chmod +x python/*.py +``` + +Then run directly: +```bash +./python/hello_world.py +./python/example_utils.py +``` + +Or use Python interpreter: +```bash +python python/hello_world.py +python python/example_utils.py +``` + +## Using uv (included in devbox) + +The devbox configuration includes `uv`, a fast Python package installer: + +```bash +# Create a virtual environment +uv venv + +# Activate it +source .venv/bin/activate + +# Install packages +uv pip install requests pandas +``` + +## Writing Your Own Scripts + +Feel free to add your own Python scripts to this directory. Follow these best practices: + +1. Include a shebang line: `#!/usr/bin/env python3` +2. Add a module docstring +3. Use type hints for better code clarity +4. Add a `main()` function +5. Use `if __name__ == "__main__":` guard diff --git a/python/example_utils.py b/python/example_utils.py new file mode 100755 index 0000000..ee44cfb --- /dev/null +++ b/python/example_utils.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +""" +Example Python utilities for devbox-config environment. + +This script demonstrates various Python capabilities and patterns +useful in a development environment. +""" + +import json +import subprocess +import sys +from pathlib import Path +from typing import Dict, List, Optional + + +def run_command(cmd: List[str]) -> Dict[str, any]: + """ + Execute a shell command and return results. + + Args: + cmd: Command as list of strings + + Returns: + Dict with stdout, stderr, and return code + """ + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=30 + ) + return { + "stdout": result.stdout, + "stderr": result.stderr, + "returncode": result.returncode, + "success": result.returncode == 0 + } + except subprocess.TimeoutExpired: + return { + "stdout": "", + "stderr": "Command timed out", + "returncode": -1, + "success": False + } + except Exception as e: + return { + "stdout": "", + "stderr": str(e), + "returncode": -1, + "success": False + } + + +def check_devbox_packages() -> List[Dict[str, str]]: + """ + Read devbox.json and list installed packages. + + Returns: + List of package information dictionaries + """ + devbox_json = Path(__file__).parent.parent / "devbox.json" + + if not devbox_json.exists(): + print(f"Error: {devbox_json} not found", file=sys.stderr) + return [] + + with open(devbox_json, 'r') as f: + config = json.load(f) + + packages = config.get("packages", []) + return [{"name": pkg.split("@")[0], "version": pkg.split("@")[1] if "@" in pkg else "latest"} + for pkg in packages] + + +def find_files(directory: Path, pattern: str = "*") -> List[Path]: + """ + Recursively find files matching a pattern. + + Args: + directory: Directory to search + pattern: Glob pattern to match + + Returns: + List of matching file paths + """ + return list(Path(directory).rglob(pattern)) + + +def format_size(bytes: int) -> str: + """ + Format bytes to human-readable size. + + Args: + bytes: Size in bytes + + Returns: + Formatted string (e.g., "1.5 MB") + """ + for unit in ['B', 'KB', 'MB', 'GB', 'TB']: + if bytes < 1024.0: + return f"{bytes:.1f} {unit}" + bytes /= 1024.0 + return f"{bytes:.1f} PB" + + +def analyze_directory(path: str = ".") -> Dict[str, any]: + """ + Analyze a directory and return statistics. + + Args: + path: Directory path to analyze + + Returns: + Dictionary with directory statistics + """ + directory = Path(path) + + if not directory.exists(): + return {"error": "Directory does not exist"} + + files = list(directory.rglob("*")) + total_size = sum(f.stat().st_size for f in files if f.is_file()) + + extensions = {} + for f in files: + if f.is_file(): + ext = f.suffix or "no_extension" + extensions[ext] = extensions.get(ext, 0) + 1 + + return { + "path": str(directory.absolute()), + "total_files": len([f for f in files if f.is_file()]), + "total_dirs": len([f for f in files if f.is_dir()]), + "total_size": format_size(total_size), + "file_types": extensions + } + + +def main(): + """Main function demonstrating the utilities.""" + print("=== Devbox Configuration Python Example ===\n") + + # Example 1: Check devbox packages + print("1. Installed Devbox Packages:") + packages = check_devbox_packages() + for pkg in packages[:5]: # Show first 5 + print(f" - {pkg['name']} ({pkg['version']})") + if len(packages) > 5: + print(f" ... and {len(packages) - 5} more packages") + print() + + # Example 2: Run a simple command + print("2. System Information:") + result = run_command(["python", "--version"]) + if result["success"]: + print(f" {result['stdout'].strip()}") + print() + + # Example 3: Analyze current directory + print("3. Directory Analysis (python/):") + stats = analyze_directory("python") + if "error" not in stats: + print(f" Total files: {stats['total_files']}") + print(f" Total size: {stats['total_size']}") + print() + + # Example 4: Find Python files + print("4. Finding Python files:") + py_files = find_files(Path(__file__).parent.parent, "*.py") + for py_file in py_files: + print(f" - {py_file}") + print() + + print("=== Example Complete ===") + + +if __name__ == "__main__": + main() diff --git a/python/hello_world.py b/python/hello_world.py new file mode 100755 index 0000000..c145698 --- /dev/null +++ b/python/hello_world.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +""" +Simple Hello World example in Python. + +This demonstrates basic Python script structure and execution. +""" + + +def greet(name: str = "World") -> str: + """Return a greeting message.""" + return f"Hello, {name}!" + + +def main(): + """Main function.""" + print(greet()) + print(greet("Devbox User")) + + # Show Python version + import sys + print(f"\nRunning Python {sys.version}") + + +if __name__ == "__main__": + main()