──────────────────────────────────────

39. Build Tools for Repeated Tasks · Give a Tool Named Options

Use argparse to parse a repeatable command and convert an option value.

Lesson files · lessons/command-line-tools/argument-parser

Before you start
- Use a named option with a default in an argument parser.
- Read a string from Program input and put it inside a list.

By the end
- Pass a typed --copies option to the parser and use the integer it returns.
- Predict the option value when the caller supplies an empty argument list.

Where you can use it
Let a colleague set the copy count with a named option they can read directly in a saved command.

In a terminal command such as python3 main.py --limit 2, the 2 is the value of --limit. In the example, parse_args(["--limit", "2"]) gives the parser those same two strings directly. With type=int, the parser turns the second string into a number you can read as args.limit.

For the challenge, read the copy count with input(), then use that value to build the argument list in Studio. To run your script from the terminal, call parse_args() with empty parentheses. The parser reads the option and value that follow main.py in the command.

Predict
What value does the example print for parse_args([])?
- 4
- 2

Worked example (example.py)

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--limit", type=int, default=4)
args = parser.parse_args(["--limit", "2"])
print(args.limit)


Example result
2

Read a number and pass it as the value of --copies. Convert it using argparse and print Copies: followed by the number.

Starter program (starter.py)

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--limit", type=int, default=4)
args = parser.parse_args(["--limit", "2"])
print(args.limit)


Hint
Build the list ["--copies", input()] and pass it to parse_args.

Case 1. Try the sample
Input
3
Expected output
Copies: 3

Case 2. Single copy
Input
1
Expected output
Copies: 1

Case 3. Explicit zero
Input
0
Expected output
Copies: 0

Stretch
Save your code as main.py in a practice folder and change the call to parse_args(). In that folder run python3 main.py --copies 3, or py main.py --copies 3 on Windows. Then replace --copies 3 with --help and find the option in the usage text.

Reflect
Why would a named option be clearer than an unexplained second input?

Check your prediction
4 An empty argument list uses the default.
