Files
mytoolkit/bin/utils.py
T
Zhengshou Lai c1df4098b3 refactor: rename package from mytoolkit to bin
- Move all source files from mytoolkit/ to bin/
- Update entry point and build config in pyproject.toml
- Add pillow and pypdf dependencies
- Update README and .gitignore paths
- Remove unused subprocess import in pdf.py
- Clean up duplicate imports in pdf merge command
2026-04-26 09:56:29 +08:00

43 lines
1.2 KiB
Python

"""Utility functions and decorators for bin."""
import functools
import subprocess
import click
def handle_errors(func):
"""Decorator to handle common errors gracefully."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except FileNotFoundError as e:
click.secho(f"Command not found: {e.filename}", fg="red", err=True)
raise click.Exit(1)
except subprocess.CalledProcessError as e:
click.secho(f"Command failed with exit code {e.returncode}", fg="red", err=True)
if e.stderr:
click.echo(e.stderr, err=True)
raise click.Exit(1)
except KeyboardInterrupt:
click.echo("\nAborted.")
raise click.Exit(130)
return wrapper
def run_command(cmd: list[str], check: bool = True, **kwargs) -> subprocess.CompletedProcess:
"""Run a subprocess command with consistent error handling.
Args:
cmd: Command and arguments as list
check: Whether to check return code
**kwargs: Additional args for subprocess.run
Returns:
CompletedProcess instance
"""
return subprocess.run(cmd, check=check, **kwargs)