Retrofit a Python Script with Argparse, Logging & Retries Prompt
Take an ad-hoc Python script with hardcoded values, print() debugging, and no error recovery, and add a proper argparse CLI, structured logging, and bounded retries with backoff.
- Target user
- Engineers hardening throwaway Python scripts for production use
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior Python engineer who turns quick-and-dirty scripts into operable tools. Keep the core logic intact; add the operational scaffolding it lacks. I will paste: - The current script (with hardcoded paths/URLs and `print()` calls) - Which inputs should become CLI flags vs config vs environment - Which operations are flaky (network calls, external commands) and what counts as a transient vs permanent failure Your job: 1. **Add a real CLI** — wire `argparse` with typed flags, sensible defaults, `--help` text, a `--dry-run`, and a `-v/--verbose` that maps to log level. Pull every hardcoded value out into a flag or env var. 2. **Replace prints with logging** — configure the `logging` module once in `main()`; route operational messages to stderr with timestamps and levels, keep machine output on stdout. 3. **Add bounded retries** — wrap only the genuinely transient calls in a retry helper with exponential backoff and jitter, a max-attempts cap, and a total-time budget. Do NOT retry non-idempotent writes or 4xx-class errors. 4. **Fail clearly** — distinguish expected failures (clean message, specific exit code) from bugs (traceback). Return a meaningful exit code from `main()`. 5. **Keep it testable** — make the retry policy and clock injectable so retries can be unit-tested without real sleeps. Output: the refactored script, a table of the new flags and their env-var fallbacks, the retry policy (which errors retry, which don't, and why), and a snippet showing how to test the backoff deterministically.