A command-line interface maps argument text to a program operation and communicates failure through errors and exit behavior.
Python receipt CLI project: parse options and report failed input
Operation contract
The parser defines required quantity and unit-minor options with a custom positive-integer type. It parses an explicit local argument list for repeatable testing instead of depending on the test runner’s arguments. Valid input produces an integer total; invalid quantity produces ArgumentError in this teaching parser configuration.
Failure and ownership boundary
The parser uses exit_on_error=False so the local test can observe the conversion error without terminating the process. A deployed CLI must define which failures exit, how stderr is used and whether any output file was already written. Python modules: separate import-time definitions from program execution and Python pathlib files: specify encoding and close the resource owner remain part of that application boundary.
Working program
import argparse
def positive_integer(text):
value = int(text)
if value <= 0:
raise argparse.ArgumentTypeError("positive integer required")
return value
def parser():
options = argparse.ArgumentParser(exit_on_error=False)
options.add_argument("--quantity", type=positive_integer, required=True)
options.add_argument("--unit-minor", type=positive_integer, required=True)
return options
if __name__ == "__main__":
options = parser().parse_args(["--quantity", "3", "--unit-minor", "125"])
print(options.quantity * options.unit_minor)
try:
parser().parse_args(["--quantity", "-1", "--unit-minor", "125"])
except argparse.ArgumentError:
print("option rejected")Output
375
option rejectedCosts and limits
This fixture parses four small tokens and performs one multiplication. It is a checked CLI boundary, not an installed package or a durable billing application; input digit limits remain a deployment choice.
Common Mistakes
- Do not parse a test runner’s arguments as application input.
- Define failure output and exit status deliberately.
Connected lessons
Python modules: separate import-time definitions from program execution, Python functions: define units, validate input and return a result, Python input exercise: accept an explicit integer grammar.
Apply this boundary
Python SQLite project: transactional batches, duplicate IDs and reopen checks, Python package layout: owned imports and module entrypoints.
