Command Palette

Search for a command to run...

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

argparse: arguments, defaults and --help

The prog name in the usage line is main.py. parse_args receives a fixed list so the example is repeatable.

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?

argparse: arguments, defaults and --help
Sign in to run this example in your browser.

Expected output

Namespace(name='Asha', times=2, shout=True)
HELLO, ASHA!
HELLO, ASHA!
Namespace(name='Ben', times=1, shout=False)

usage: main.py [-h] [--times TIMES] [--shout] name

Greet someone.

positional arguments:
  name           who to greet

options:
  -h, --help     show this help message and exit
  --times TIMES  how many greetings
  --shout        use capital letters