Command-line programs
Overview
So far your programs have asked questions with input(). Real tools usually take their instructions on the command line, like git commit -m "message" or pip install requests. That makes them fast to use, easy to script, and easy to run on a schedule. This lesson turns a script into a proper command-line program.
sys.argv: the raw words
When you run python greet.py Asha --loud, Python puts the words in sys.argv:
# greet.py
import sys
print(sys.argv)$ python greet.py Asha --loud
['greet.py', 'Asha', '--loud']sys.argv[0] is the script name; the rest are the arguments, always as strings. You could process them by hand — but then you’d have to check how many there are, convert types, handle typos, and write help text. That’s what argparse does for you.
argparse
# todo.py
import argparse
parser = argparse.ArgumentParser(description="A tiny to-do list")
parser.add_argument("text", help="what to do")
parser.add_argument("--priority", choices=["low", "high"], default="low")
args = parser.parse_args()
print(f"Added: {args.text} ({args.priority} priority)")$ python todo.py "Buy milk" --priority high
Added: Buy milk (high priority)Three steps: create a parser, add arguments, parse. The result, args, has one attribute per argument.
Free help and error messages
$ python todo.py --help
usage: todo.py [-h] [--priority {low,high}] text
A tiny to-do list
positional arguments:
text what to do
options:
-h, --help show this help message and exit
--priority {low,high}$ python todo.py --priority urgent
usage: todo.py [-h] [--priority {low,high}] text
todo.py: error: argument --priority: invalid choice: 'urgent' (choose from 'low', 'high')argparse checks the input, prints a clear message and exits with code 2 — you wrote none of that.
Kinds of arguments
parser.add_argument("bill", type=float) # positional, converted to float
parser.add_argument("--people", type=int, default=1) # option with a value
parser.add_argument("-v", "--verbose", action="store_true") # flag: True if present
parser.add_argument("--tag", action="append") # repeatable: --tag a --tag b
parser.add_argument("files", nargs="+") # one or more values
parser.add_argument("--output", required=True) # an option that must be given- Positional arguments are identified by position and are required (unless
nargs="?"). - Options start with
--(and can have a short form like-v); they’re optional unlessrequired=True. type=converts the text and reports an error if it can’t.- A dash in an option name becomes an underscore in
args:--round-up→args.round_up.
Subcommands
Bigger tools have subcommands, each with its own arguments — git commit, git log, pip install:
parser = argparse.ArgumentParser(prog="notes")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", help="add a note")
add.add_argument("text")
show = sub.add_parser("list", help="list notes")
show.add_argument("--limit", type=int, default=10)
args = parser.parse_args()
if args.command == "add":
...
elif args.command == "list":
...python notes.py add "Call Asha" and python notes.py list --limit 5 now both work, each with its own --help. The final project uses exactly this structure.
stdout, stderr and exit codes
Command-line programs talk to the outside world in three ways:
- stdout — normal output (
print()), which can be redirected to a file or piped to another program; - stderr — error messages:
print("error: …", file=sys.stderr). They still appear in the terminal even when stdout is redirected; - the exit code —
0means success, anything else means failure. Scripts, CI systems and other programs check it.
import sys
def main():
...
if problem:
print("error: file not found", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())Check the exit code of the last command with echo $? (macOS/Linux) or echo $LASTEXITCODE (PowerShell).
Structuring the program as main() returning an exit code keeps everything testable: tests can call main() directly. Passing a list — parser.parse_args(["50", "--people", "2"]) — lets tests supply arguments without a terminal.
Reading from pipes
Good command-line tools can read from other programs. sys.stdin is a file-like object:
import sys
for line in sys.stdin:
print(line.upper(), end="")$ cat notes.txt | python shout.pyMaking it feel like a real command
- Run a package with
python -m yourpackageby adding a__main__.pyfile (as in the final project). - With a
[project.scripts]entry inpyproject.toml, installing the project creates a real command:
[project.scripts]
tip = "tip:main"After pip install -e . (or uv tool install .), you can type tip 50 --people 2 anywhere.
For fancier tools, popular third-party libraries include Typer and Click (arguments from function signatures) and Rich (colours, tables and progress bars).
Recipe: argparse for arguments,
main()returning an exit code, errors to stderr,sys.exit(main())at the bottom.
A tip calculator tool
Write tip.py, a command-line tool. It takes a required positional bill (a float), an optional --tip percentage (float, default 15), an optional --people count (int, default 1) and a --round-up flag. It prints the tip, the total and the amount per person, each with 2 decimal places; with --round-up, the per-person amount is rounded up to the next whole number with math.ceil. If people is less than 1, print an error to stderr and exit with code 1. Try python tip.py 87.40 --tip 12.5 --people 3, python tip.py 50 --round-up --people 3 and python tip.py --help.
# tip.py
import argparse
import math
import sys
def main():
parser = argparse.ArgumentParser(description="Split a restaurant bill.")
# add arguments here
args = parser.parse_args()
if __name__ == "__main__":
main()# tip.py
import argparse
import math
import sys
def main():
parser = argparse.ArgumentParser(description="Split a restaurant bill.")
parser.add_argument("bill", type=float, help="the bill before tip")
parser.add_argument("--tip", type=float, default=15, help="tip percentage (default: 15)")
parser.add_argument("--people", type=int, default=1, help="number of people (default: 1)")
parser.add_argument("--round-up", action="store_true", help="round each share up to a whole number")
args = parser.parse_args()
if args.people < 1:
print("error: --people must be at least 1", file=sys.stderr)
return 1
tip = args.bill * args.tip / 100
total = args.bill + tip
share = total / args.people
if args.round_up:
share = math.ceil(share)
print(f"Tip: {tip:.2f}")
print(f"Total: {total:.2f}")
print(f"Per person: {share:.2f}")
return 0
if __name__ == "__main__":
sys.exit(main())Summary
sys.argvis the list of words typed on the command line;sys.argv[0]is the script name.- argparse turns arguments into a validated object (
args.bill), converts types, and writes--helpautomatically. - Positional arguments are required; options start with
--, can have defaults, andaction="store_true"makes a flag. - Print errors to
sys.stderrand exit with a non-zero code (sys.exit(1)) so scripts and other tools can detect failure. - Subcommands (
add,list,report) useadd_subparsers— the structure behind tools like git and pip.