Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:00:18 +08:00
commit 765529cd13
69 changed files with 18291 additions and 0 deletions

View File

@@ -0,0 +1,72 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "httpx>=0.27.0",
# "rich>=13.0.0",
# ]
# ///
"""
API client template using httpx.
Demonstrates HTTP requests, error handling, and structured output.
Includes environment variable usage for API credentials.
Usage:
export API_URL="https://api.example.com"
export API_TOKEN="your-token"
python api-client.py
"""
import httpx
import os
import sys
from rich import print
from rich.console import Console
console = Console()
def get_env_var(name: str) -> str:
"""Get required environment variable or exit with error."""
value = os.getenv(name)
if not value:
console.print(f"[red]Error: {name} environment variable not set[/red]")
sys.exit(1)
return value
def fetch_data(api_url: str, token: str):
"""Fetch data from API with error handling."""
headers = {"Authorization": f"Bearer {token}"}
try:
with httpx.Client() as client:
response = client.get(api_url, headers=headers, timeout=10.0)
response.raise_for_status()
return response.json()
except httpx.HTTPStatusError as e:
console.print(f"[red]HTTP error {e.response.status_code}[/red]")
console.print(f"Response: {e.response.text}")
sys.exit(1)
except httpx.RequestError as e:
console.print(f"[red]Request failed: {e}[/red]")
sys.exit(1)
def main():
"""Main entry point."""
api_url = get_env_var("API_URL")
api_token = get_env_var("API_TOKEN")
console.print(f"[cyan]Fetching data from {api_url}...[/cyan]")
data = fetch_data(api_url, api_token)
# Process and display data
print(data)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,24 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""
Basic Python script template using uv.
This is a minimal working example showing the correct PEP 723 format.
No external dependencies - uses only Python standard library.
Usage:
python basic-script.py
"""
def main():
"""Main entry point for the script."""
print("Hello from uv!")
# Your code here
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,62 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "typer>=0.9.0",
# "rich>=13.0.0",
# ]
# ///
"""
CLI application template using Typer and Rich.
Demonstrates command-line argument parsing, subcommands, and formatted output.
Usage:
python cli-app.py --help
python cli-app.py greet "World"
python cli-app.py process input.txt --output output.txt
"""
import typer
from rich import print
from rich.console import Console
from pathlib import Path
app = typer.Typer()
console = Console()
@app.command()
def greet(name: str):
"""Greet someone by name."""
print(f"[green]Hello, {name}![/green]")
@app.command()
def process(
input_file: Path = typer.Argument(..., help="Input file to process"),
output: Path = typer.Option(None, "--output", "-o", help="Output file path"),
):
"""Process a file and optionally write results."""
if not input_file.exists():
console.print(f"[red]Error: {input_file} not found[/red]")
raise typer.Exit(code=1)
# Process file
with open(input_file) as f:
content = f.read()
console.print(f"[cyan]Processing {input_file}...[/cyan]")
# Your processing logic here
result = content.upper() # Example transformation
if output:
output.write_text(result)
console.print(f"[green]✓ Written to {output}[/green]")
else:
print(result)
if __name__ == "__main__":
app()

View File

@@ -0,0 +1,84 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "polars>=0.20.0",
# "rich>=13.0.0",
# ]
# ///
"""
Data processing template using Polars.
Demonstrates reading, transforming, and analyzing data with
modern data processing libraries.
Usage:
python data-processor.py input.csv
python data-processor.py data/*.csv --output results/
"""
import sys
from pathlib import Path
import polars as pl
from rich.console import Console
from rich.table import Table
console = Console()
def process_csv(file_path: Path) -> pl.DataFrame:
"""Read and process a CSV file."""
try:
df = pl.read_csv(file_path)
console.print(f"[cyan]Loaded {len(df)} rows from {file_path.name}[/cyan]")
# Example transformations
# df = df.filter(pl.col("status") == "active")
# df = df.with_columns(pl.col("amount").cast(pl.Float64))
return df
except Exception as e:
console.print(f"[red]Error processing {file_path}: {e}[/red]")
sys.exit(1)
def display_summary(df: pl.DataFrame):
"""Display data summary using Rich tables."""
table = Table(title="Data Summary")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="green")
table.add_row("Total Rows", str(len(df)))
table.add_row("Columns", str(len(df.columns)))
# Example statistics
# if "amount" in df.columns:
# table.add_row("Total Amount", f"${df['amount'].sum():,.2f}")
console.print(table)
def main():
"""Main entry point."""
if len(sys.argv) < 2:
console.print("[red]Usage: python data-processor.py <input.csv>[/red]")
sys.exit(1)
input_path = Path(sys.argv[1])
if not input_path.exists():
console.print(f"[red]Error: {input_path} not found[/red]")
sys.exit(1)
df = process_csv(input_path)
display_summary(df)
# Optional: Save results
# output_path = Path("output.csv")
# df.write_csv(output_path)
# console.print(f"[green]✓ Saved to {output_path}[/green]")
if __name__ == "__main__":
main()