Command-Line Tools
Programs that people can run.
Ava's friend runs a flower stall, and wants to use her price calculator. But she does not know Python. A good command line tool is simple to use. She types a command, with a few options, and gets an answer. Python makes that easy, with the argparse module, which even writes the help page for you.

- Share your code with non programmers
- A command with options
- argparse builds the interface
Reading arguments
The argparse module defines the arguments your program accepts. Add argument for each one, with a name, a type, and a help text. Parse args reads the command line. Here we simulate a command line by passing a list, so you see the result of a typical call, with a price, a quantity, and a discount option.
import argparse
parser = argparse.ArgumentParser(description="Price calculator")
parser.add_argument("price", type=float, help="unit price")
parser.add_argument("qty", type=int, help="quantity")
parser.add_argument("--discount", type=float, default=0, help="percent off")
args = parser.parse_args(["9.5", "4", "--discount", "10"])
total = args.price * args.qty * (1 - args.discount / 100)
print(f"Total: ${total:.2f}")Total: $34.20
Automatic help and flags
The help page is generated for you, from the descriptions. Flags, with the store true action, switch features on. Choices restrict values to a list. And when the user makes a mistake, argparse prints a clear message, and exits. All the friendly behaviour of professional tools, for free.
import argparse
p = argparse.ArgumentParser(prog="leafy", description="Leafy Corner tools")
p.add_argument("plant", choices=["fern", "ivy", "rose"])
p.add_argument("--gift", action="store_true", help="add gift wrap")
p.print_help()
print("---")
print(p.parse_args(["ivy", "--gift"]))usage: leafy [-h] [--gift] {fern,ivy,rose}
Leafy Corner tools
positional arguments:
{fern,ivy,rose}
options:
-h, --help show this help message and exit
--gift add gift wrap
---
Namespace(plant='ivy', gift=True)Making scripts executable
To run your tool like a real command, add a shebang line at the top, which names the interpreter, and make the file executable. Wrap your logic in a main function, called from the main guard. Return an exit code, zero for success, and non zero for failure, so other programs can react. Later, packaging lets users install your tool with a single pip command.
A greeting tool
Your turn. Build an argument parser with one required name argument, and an optional shout flag. Parse a test command line, and print the greeting, in upper case, if the flag is set. Ready? Here is one solution. An argument, a store true flag, and a simple if.
Create a parser with a "name" argument and a --shout flag; parse ["Ava", "--shout"] and print the greeting.
Show hint
action="store_true"
Show solution
import argparse
p = argparse.ArgumentParser()
p.add_argument("name")
p.add_argument("--shout", action="store_true")
args = p.parse_args(["Ava", "--shout"])
msg = f"Hello, {args.name}!"
print(msg.upper() if args.shout else msg)HELLO, AVA!
Summary
Great work. You can build command line tools with argparse, add options, flags and automatic help, and return clean exit codes. Next, we open the doors of data science, with numpy, pandas and matplotlib.
Key takeaways- argparse: arguments, flags, help
- main() + __name__ guard
- Exit codes for other programs