Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 17.8 — Capstone: CLI, Config, Logging and Streaming
Python · Example 1 of 2

argparse, Config and logging, called with fixed arguments

Add an option such as '--docs other' and print it back, or change 'DOCQA_MODEL' in the env dictionary.

Turn the core library into a real command-line tool: argparse arguments, configuration from the environment with secrets handled safely, logging that helps you debug, clean error handling, streamed output, and retries with backoff.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a parser with a required positional name and an optional --times integer defaulting to 1, and call parse_args with a fixed list to show the result.

02

Write describe_config(env) that returns a string listing DOCQA_MODEL and whether DOCQA_API_KEY is set, without ever including the key value.

03

Write a function backoff_delays(attempts, base) returning the list of waits [base, base*2, base*4, ...] for the given number of retries.

Explain it without notes

01

Why should main accept argv as a parameter and return an exit code?

02

How do you handle secrets in a CLI tool?

03

When should you retry a failed API call, and how?

04

What is the difference between print and logging, and where should each go?

05

You wrap a streaming call in a retry loop, but the retry never fires. Why, and how do you retry a stream correctly?

argparse, Config and logging, called with fixed arguments
Sign in to run this example in your browser.

Expected output

DEBUG docqa: config: docs=docs top_k=2 model=fake api_key=missing
WARNING docqa: no API key set, using the fake model
asking 'fake': What is the refund policy?
exit code: 0
ERROR docqa: --top-k must be at least 1
exit code: 2
usage: docqa [-h] [--docs DOCS] [--top-k TOP_K] [-v] question
docqa: error: the following arguments are required: question
no question given -> SystemExit 2