Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Python as a system
EXPERIMENT 42 / 101

Give your script a front door.

Accept named arguments, validate them, and offer built-in help.

ADVANCED LAB
BY NAVAN SAMI◷ 11 MIN READPYTHON 3

01 The idea

A command-line interface turns a script into a tool someone can use without editing its source. argparse defines accepted options, converts basic types, and generates help. Keep argument parsing at the edge and pass validated values to ordinary functions. That separation makes behaviour easier to test independently of the terminal.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

command_line_tools.py
import argparse

def parser():
    command = argparse.ArgumentParser(description="Estimate a mission")
    command.add_argument("name")
    command.add_argument("--minutes", type=int, default=30)
    return command

args = parser().parse_args(["Orbit", "--minutes", "45"])
if args.minutes <= 0:
    raise ValueError("minutes must be positive")
print(f"{args.name}: {args.minutes} minutes")
↳ EXPECTED OUTPUT
Orbit: 45 minutes

03 Under the hood

  1. 1

    The explicit list makes the example reproducible. In a real entry point call parse_args() without a list to read the process arguments.

  2. 2

    type=int converts a syntactically valid integer, but a negative value still needs application validation. Use parser.error for a friendly CLI-level validation message.

  3. 3

    argparse supplies --help automatically. Give errors nonzero exit status, reserve standard output for the tool’s useful result, and send diagnostics to standard error.

04 Your turn, builder

A SMALL MISSION

Add a --verbose boolean flag and show that it becomes True when supplied.

Reveal one possible solution +
one_possible_solution.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", action="store_true")
args = parser.parse_args(["--verbose"])
print(args.verbose)

05 Check your signal

QUICK SIGNAL CHECK

What does store_true do for a flag?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.