Command-line programs

Topic 3 of 4 in Tools and projects7 min readBeginnerFree course

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:

Python
# greet.py
import sys
print(sys.argv)
Text
$ 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

Anatomy of a command-line program. In $ python todo.py “Buy milk” –priority high, todo.py is the script, “Buy milk” is a positional argument, and –priority high is an option with a value. The code: parser = argparse.ArgumentParser(description=“A tiny to-do list”); parser.add_argument(“text”); parser.add_argument(“–priority”, choices=[“low”, “high”], default=“low”); args = parser.parse_args() — giving args.text and args.priority, plus free –help. sys.argv holds the raw words; argparse validates them, converts types and writes the –help text.

Python
# 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)")
Text
$ 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

Text
$ 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}
Text
$ 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

Python
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 unless required=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:

Python
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 — 0 means success, anything else means failure. Scripts, CI systems and other programs check it.
Python
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:

Python
import sys

for line in sys.stdin:
    print(line.upper(), end="")
Text
$ cat notes.txt | python shout.py

Making it feel like a real command

  • Run a package with python -m yourpackage by adding a __main__.py file (as in the final project).
  • With a [project.scripts] entry in pyproject.toml, installing the project creates a real command:
TOML
[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.

Exercise

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.

Python
# 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()

Summary

  • sys.argv is 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 --help automatically.
  • Positional arguments are required; options start with --, can have defaults, and action="store_true" makes a flag.
  • Print errors to sys.stderr and exit with a non-zero code (sys.exit(1)) so scripts and other tools can detect failure.
  • Subcommands (add, list, report) use add_subparsers — the structure behind tools like git and pip.