Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.7 — Command-Line Tools: argparse and Typer
Python · Example 2 of 2

Subcommands, a main() that returns an exit code, and SystemExit

The bad call (task id 'three') makes argparse print to the error stream and raise SystemExit(2).

A command-line tool reads its settings from the words typed after its name. Python's argparse module turns sys.argv into a clean object, builds --help for free, rejects bad input with a usage message, and lets the program report success or failure through its exit code.

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 for a tool repeat with a positional word and an option --count (integer, default 2), and print the word that many times on one line.

02

Add a --upper flag to it.

03

Write main(argv) that returns 0 on success and 1 if --count is below 1 (print an error to sys.stderr).

Explain it without notes

01

What is the difference between a positional argument, an option and a flag in argparse?

02

What are exit codes, and what does argparse do on bad input?

03

How do you build a tool with subcommands, and how do you test it without a terminal?

04

Why do many tools read secrets from the environment rather than a --api-key option?

Subcommands, a main() that returns an exit code, and SystemExit
Sign in to run this example in your browser.

Expected output

added 'buy milk' with priority high
exit code: 0
finished task 3
exit code: 0
usage: todo done [-h] task_id
todo done: error: argument task_id: invalid int value: 'three'
SystemExit code: 2