← ClaudeAtlas

python-scripting-patternslisted

Python scripting best practices for automation, CLI tools, and Claude Code hooks. Use this skill whenever writing or modifying Python scripts, CLI tools, or Claude Code hooks written in Python (.py files under .claude/hooks/), automation scripts, data processing scripts, or any standalone Python utility — even for small edits, since stdin-parsing mistakes, broad except clauses, and missing exit-code discipline are easy to introduce silently and hard to debug later.
sardonyx0827/dotfiles · ★ 0 · Data & Documents · score 72
Install: claude install-skill sardonyx0827/dotfiles
# Python Scripting Patterns Best practices for Python scripts, with specific patterns for Claude Code hooks and automation on macOS. ## Script Skeleton Every standalone script uses this structure so it is importable AND runnable: ```python #!/usr/bin/env python3 """One-line description of what this script does.""" import sys def main() -> int: # ... do work ... return 0 if __name__ == "__main__": raise SystemExit(main()) ``` - `raise SystemExit(main())` propagates the integer return code to the OS without leaving a traceback on the terminal. `sys.exit()` does the same but is less idiomatic for a `main()` that already returns int. - The `def main() -> int` boundary makes the function unit-testable with `monkeypatch` without spawning a subprocess. ### Dependency policy Hooks and one-off scripts must work with stdlib only. Adding a third-party dependency to a hook means every developer needs it installed before Claude Code runs at all. ```python # ❌ WRONG: pip dependency in a hook import httpx # breaks if not installed # ✅ CORRECT: stdlib HTTP for hooks/scripts import urllib.request import urllib.error ``` When a third-party package is genuinely needed (e.g., a standalone CLI tool), use `uv` as the runner so the venv is managed automatically: ``` #!/usr/bin/env -S uv run --script # /// script # dependencies = ["httpx", "rich"] # /// ``` ## Reading JSON from stdin Safely Hooks receive structured input on stdin. Crash = the entire tool call is blocke