Give your script a front door.
Accept named arguments, validate them, and offer built-in help.
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.
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")Orbit: 45 minutes
03 Under the hood
- 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
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
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
Add a --verbose boolean flag and show that it becomes True when supplied.
Reveal one possible solution +
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", action="store_true")
args = parser.parse_args(["--verbose"])
print(args.verbose)05 Check your signal
What does store_true do for a flag?
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 ↗.