Building CLI Tools

Published by Brayan K

Build real command-line tools the same way professionals build developer utilities, automated scripts, data pipelines, AI model runners, and deployment tools. Master both argparse (standard, built-in) and Typer (modern, FastAPI-style) for creating production-grade CLI applications.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A command line reaches the program as a list of strings

This lesson builds the command-line side of a program: the words typed after its name, what it does with a wrong one, the exit status it hands back, its help and its subcommands. It uses the standard library's argparse, then Typer, which reads the same things from a function's type hints. Installing a tool as a command is in Packaging & Publishing Python Libraries to PyPI, running other programs from Python is in Running Commands with subprocess, and scripts that run on a schedule are in Automation & Scripting for DevOps and System Tasks.

Introduction to Python ran a file from a terminal, with python on Windows and python3 on macOS and Linux. Whatever you type after the file's name reaches the program in sys.argv, a list. This file prints it:

# argv.py
import sys

print(sys.argv)
python argv.py Ada --times 2 "hello world"

That prints ['argv.py', 'Ada', '--times', '2', 'hello world']. Item 0 is the script's name, every item is a string, even '2', and the quotes made hello world one item.

This site's editor has no terminal, so its sys.argv is [''], and the build that checks these examples runs each one with nothing after its name. So the examples here hand the program a list of their own, shaped like sys.argv. Reading the values by position works until someone types them in another order, or leaves one out:

def main(argv):
    name = argv[1]
    times = int(argv[2])
    for _ in range(times):
        print(f"Hello, {name}!")


main(["greet.py", "Ada", "2"])
main(["greet.py", "--times", "2", "Ada"])
main(["greet.py", "Ada"])

# ✅ Expected output:
# Hello, Ada!
# Hello, Ada!
# Hello, --times!
# Hello, --times!

# ✅ Expected error:
# IndexError: list index out of range

--times was taken as the name, and the last call had no item 2. A word where the number goes stops the program with int()'s own error, which says nothing about the command line:

def main(argv):
    name = argv[1]
    times = int(argv[2])
    for _ in range(times):
        print(f"Hello, {name}!")


main(["greet.py", "Ada", "two"])

# ✅ Expected error:
# ValueError: invalid literal for int() with base 10: 'two'

Someone using the program needs names instead of positions, a message that says which value was wrong, and a line that shows how to call it. argparse does all three.

argparse parses any list you give it

You describe the arguments, then hand parse_args() the list. A name without dashes is a positional argument, filled in the order the values come. A name that starts with -- is an option, which can come anywhere:

import argparse

parser = argparse.ArgumentParser(prog="greet", description="Say hello.")
parser.add_argument("name", help="who to greet")
parser.add_argument("--times", type=int, default=1, help="how many times")

args = parser.parse_args(["Ada", "--times", "2"])
print(args)
print(args.name, args.times)

args = parser.parse_args(["--times", "3", "Grace"])
print(args.name, args.times)

# ✅ Expected output:
# Namespace(name='Ada', times=2)
# Ada 2
# Grace 3

parse_args() returns a Namespace, which holds each argument as an attribute: args.name, args.times. prog= is the program's name in its messages, and description= heads its help.

Called with no list, parse_args() reads sys.argv[1:], everything after the program's name. So a program keeps its parser in a main(argv=None) function: in a terminal, main() gets the real arguments, while a test, or this page, calls main([...]) with a list. Testing with pytest: Fixtures, Parametrisation & Mocks tests such a function that way.

import argparse


def main(argv=None):
    parser = argparse.ArgumentParser(prog="greet")
    parser.add_argument("name")
    parser.add_argument("--times", type=int, default=1)
    args = parser.parse_args(argv)
    for _ in range(args.times):
        print(f"Hello, {args.name}!")
    return 0


if __name__ == "__main__":
    status = main(["Ada", "--times", "2"])
    print("exit status:", status)

# ✅ Expected output:
# Hello, Ada!
# Hello, Ada!
# exit status: 0

As Modules and Packages said, the program starts under if __name__ == "__main__":. Here is the whole file, with a --loud flag that a later part explains. Its last line passes main()'s return value on as the program's exit status, also explained below:

# greet.py
import argparse


def main(argv=None):
    parser = argparse.ArgumentParser(description="Say hello.")
    parser.add_argument("name", help="who to greet")
    parser.add_argument("--times", type=int, default=1, help="how many times")
    parser.add_argument("--loud", action="store_true", help="shout")
    args = parser.parse_args(argv)
    for _ in range(args.times):
        message = f"Hello, {args.name}!"
        print(message.upper() if args.loud else message)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
python greet.py Ada --times 2

That prints Hello, Ada! twice. On this page, though, parse_args() with no list finds nothing after the program's name, in the editor and in the build alike. What argparse does about that is the next big idea, so this example catches it. contextlib.redirect_stderr() is a context manager: inside its with block, whatever is written to standard error goes into an io.StringIO, the in-memory file from Reading CSV & Excel Files. contextlib: contextmanager, suppress, ExitStack covers the module.

import argparse
import contextlib
import io

parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("name")

stderr = io.StringIO()
try:
    with contextlib.redirect_stderr(stderr):
        parser.parse_args()
except SystemExit as stop:
    print("exit status:", stop.code)
print(stderr.getvalue(), end="")

# ✅ Expected output:
# exit status: 2
# usage: greet [-h] name
# greet: error: the following arguments are required: name

Without prog="greet", the name in those two lines comes from sys.argv[0]: greet.py in a terminal, but an empty string in this site's editor, and the build's own file name when it checks the example. So every example here sets prog=.

Values stay text unless you give a type

Everything on a command line is text, and argparse converts a value only when you give it type=:

import argparse

parser = argparse.ArgumentParser(prog="calc")
parser.add_argument("a")
parser.add_argument("b", type=int)

args = parser.parse_args(["2", "3"])
print(repr(args.a), repr(args.b))
print(args.a * 2, args.b * 2)

# ✅ Expected output:
# '2' 3
# 22 6

args.a is still the string '2', so * 2 repeats it. An option that isn't given gets its default=, or None without one, and action="store_true" makes a flag, which takes no value: False without it, True with it.

import argparse

parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("name")
parser.add_argument("--times", type=int, default=1)
parser.add_argument("--loud", action="store_true")

print(parser.parse_args(["Ada"]))
print(parser.parse_args(["Ada", "--loud", "--times", "3"]))

# ✅ Expected output:
# Namespace(name='Ada', times=1, loud=False)
# Namespace(name='Ada', times=3, loud=True)

type=bool looks like another way to a flag, but type= is called on the text, and bool() of any text but the empty string is True:

import argparse

parser = argparse.ArgumentParser(prog="build")
parser.add_argument("--debug", type=bool, default=False)

print(parser.parse_args(["--debug", "False"]).debug)
print(bool("False"), bool(""))

# ✅ Expected output:
# True
# True False

Use action="store_true". For a pair such as --color and --no-color, argparse has action=argparse.BooleanOptionalAction.

In the Namespace, the dashes in an option's name become underscores, since args.dry-run would read as args.dry minus run:

import argparse

parser = argparse.ArgumentParser(prog="backup")
parser.add_argument("source")
parser.add_argument("--dry-run", action="store_true")

args = parser.parse_args(["photos", "--dry-run"])
print(args)
print(args.dry_run)
print(args.dry-run)

# ✅ Expected output:
# Namespace(source='photos', dry_run=True)
# True

# ✅ Expected error:
# AttributeError: 'Namespace' object has no attribute 'dry'

A positional argument keeps its name as written: one called source-dir ends up as vars(args)["source-dir"], out of reach of a dot. Name positionals with underscores.

nargs="+" collects one value or more into a list (nargs="*" also allows none, and nargs="?" one or none). choices= allows only the values listed, and action="append" collects an option that's given more than once:

import argparse

parser = argparse.ArgumentParser(prog="pack")
parser.add_argument("files", nargs="+")
parser.add_argument("--level", choices=["low", "high"], default="low")
parser.add_argument("--tag", action="append")

print(parser.parse_args(["a.txt", "b.txt", "--tag", "x", "--tag", "y"]))
print(parser.parse_args(["a.txt", "--level", "high"]))

# ✅ Expected output:
# Namespace(files=['a.txt', 'b.txt'], level='low', tag=['x', 'y'])
# Namespace(files=['a.txt'], level='high', tag=None)

A value outside choices stops the program with an invalid choice error, whose wording changed between versions. For --speed fsat with the choices slow and fast, Python 3.10–3.12 and 3.14 say argument --speed: invalid choice: 'fsat' (choose from 'slow', 'fast'), and 3.13 leaves the quotes out of the list.

An option can still be compulsory, with required=True. And action="count" counts how often a flag appears, as in -vv; give it default=0, or it's None when the flag isn't there:

import argparse

parser = argparse.ArgumentParser(prog="deploy")
parser.add_argument("--env", required=True)
parser.add_argument("-v", "--verbose", action="count", default=0)

print(parser.parse_args(["--env", "test"]))
print(parser.parse_args(["--env", "live", "-vv"]))

# ✅ Expected output:
# Namespace(env='test', verbose=0)
# Namespace(env='live', verbose=2)

Three smaller rules: when an option is given twice, the last value wins (--times 2 --times 5 gives 5); an option's name may be shortened as long as only one option starts that way (--ti 4 for --times 4); and -- ends the options, so in -- -weird-name the second word is a positional value, dash and all.

A wrong command line stops the program with exit status 2

When a command line doesn't fit the parser, argparse doesn't hand your code a bad value. In a terminal, with greet.py:

python greet.py
python greet.py --times two Ada
python greet.py Ada --colour red

None of them prints anything on standard output, the stream print() writes to. On standard error, the stream for messages about problems, the first prints usage: greet.py [-h] [--times TIMES] [--loud] name and then greet.py: error: the following arguments are required: name. The second ends with argument --times: invalid int value: 'two', and the third with unrecognized arguments: --colour red. Each stops before any of your code after parse_args() runs, with exit status 2.

It stops by raising SystemExit. This site's editor shows that as an error, SystemExit: 2, and preserves argparse's standard-error lines before the error report. The examples here catch it and print the captured messages with the exit status so both are easy to inspect:

import argparse
import contextlib
import io

parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("name")
parser.add_argument("--times", type=int, default=1)

stderr = io.StringIO()
try:
    with contextlib.redirect_stderr(stderr):
        parser.parse_args(["Ada", "--times", "two"])
except SystemExit as stop:
    print("exit status:", stop.code)
print(stderr.getvalue(), end="")

# ✅ Expected output:
# exit status: 2
# usage: greet [-h] [--times TIMES] name
# greet: error: argument --times: invalid int value: 'two'

Exception Handling showed that SystemExit isn't an Exception, so except Exception lets it through:

import argparse

parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("--times", type=int, default=1)

try:
    parser.parse_args(["--times", "two"])
except Exception:
    print("except Exception caught it")
except SystemExit as stop:
    print("except SystemExit caught it, code", stop.code)

# ✅ Expected output:
# except SystemExit caught it, code 2

A helper that returns the status and the error line shows five common mistakes at once:

import argparse
import contextlib
import io


def error_of(parser, argv):
    stderr = io.StringIO()
    try:
        with contextlib.redirect_stderr(stderr):
            parser.parse_args(argv)
    except SystemExit as stop:
        return f"exit status {stop.code}: {stderr.getvalue().splitlines()[-1]}"
    return "no error"


parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("name")
parser.add_argument("--times", type=int, default=1)

for argv in ([], ["Ada", "--times", "two"], ["Ada", "--times"], ["Ada", "--colour", "red"], ["Ada", "Bob"]):
    print(argv, "->", error_of(parser, argv))

# ✅ Expected output:
# [] -> exit status 2: greet: error: the following arguments are required: name
# ['Ada', '--times', 'two'] -> exit status 2: greet: error: argument --times: invalid int value: 'two'
# ['Ada', '--times'] -> exit status 2: greet: error: argument --times: expected one argument
# ['Ada', '--colour', 'red'] -> exit status 2: greet: error: unrecognized arguments: --colour red
# ['Ada', 'Bob'] -> exit status 2: greet: error: unrecognized arguments: Bob

Your own checks can stop the program the same way. type= takes any function that turns the text into a value: one that raises argparse.ArgumentTypeError gives your message, and one that raises ValueError gives argparse's invalid … value message, with the function's name in it:

import argparse
import contextlib
import io


def error_of(parser, argv):
    stderr = io.StringIO()
    try:
        with contextlib.redirect_stderr(stderr):
            parser.parse_args(argv)
    except SystemExit as stop:
        return f"exit status {stop.code}: {stderr.getvalue().splitlines()[-1]}"
    return "no error"


def positive_int(text):
    number = int(text)
    if number <= 0:
        raise argparse.ArgumentTypeError(f"{number} is not a positive number")
    return number


parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("--times", type=positive_int, default=1)

print(parser.parse_args(["--times", "3"]))
print(error_of(parser, ["--times", "0"]))
print(error_of(parser, ["--times", "x"]))

# ✅ Expected output:
# Namespace(times=3)
# exit status 2: greet: error: argument --times: 0 is not a positive number
# exit status 2: greet: error: argument --times: invalid positive_int value: 'x'

A rule about two arguments together goes in parser.error(), which prints the usage and your message and stops with status 2 as well:

import argparse
import contextlib
import io

parser = argparse.ArgumentParser(prog="copy")
parser.add_argument("source")
parser.add_argument("target")

args = parser.parse_args(["notes.txt", "notes.txt"])
stderr = io.StringIO()
try:
    with contextlib.redirect_stderr(stderr):
        if args.source == args.target:
            parser.error("source and target are the same file")
except SystemExit as stop:
    print("exit status:", stop.code)
print(stderr.getvalue(), end="")

# ✅ Expected output:
# exit status: 2
# usage: copy [-h] source target
# copy: error: source and target are the same file

add_mutually_exclusive_group() allows at most one of its options, and with required=True exactly one:

import argparse
import contextlib
import io


def error_of(parser, argv):
    stderr = io.StringIO()
    try:
        with contextlib.redirect_stderr(stderr):
            parser.parse_args(argv)
    except SystemExit as stop:
        return f"exit status {stop.code}: {stderr.getvalue().splitlines()[-1]}"
    return "no error"


parser = argparse.ArgumentParser(prog="report")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--json", action="store_true")
group.add_argument("--csv", action="store_true")

print(parser.parse_args(["--csv"]))
print(error_of(parser, ["--json", "--csv"]))
print(error_of(parser, []))

# ✅ Expected output:
# Namespace(json=False, csv=True)
# exit status 2: report: error: argument --csv: not allowed with argument --json
# exit status 2: report: error: one of the arguments --json --csv is required

parse_known_args() doesn't stop at arguments it doesn't know. It returns them with the Namespace, for a program that hands the rest on to another:

import argparse

parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("name")

args, extra = parser.parse_known_args(["Ada", "--colour", "red"])
print(args)
print(extra)

# ✅ Expected output:
# Namespace(name='Ada')
# ['--colour', 'red']

The exit status tells whoever ran the program how it went

Every program ends with an exit status, a number for whatever started it: 0 means success, and anything else a failure. argparse uses 2 for a wrong command line. A shell script, a scheduled job or a test run on every push checks it, as Automation & Scripting for DevOps and System Tasks shows, and Running Commands with subprocess reads it from the other side.

sys.exit() ends a program by raising SystemExit with what you give it. A number becomes the status, None means 0, and text is printed on standard error with status 1:

import sys

for value in (0, 3, "error: no input file", None):
    try:
        sys.exit(value)
    except SystemExit as stop:
        print(repr(stop.code))

# ✅ Expected output:
# 0
# 3
# 'error: no input file'
# None

So main() returns the status, and the file's last line passes it on, as in greet.py above. The examples here print it instead:

import argparse


def main(argv=None):
    parser = argparse.ArgumentParser(prog="check")
    parser.add_argument("path")
    args = parser.parse_args(argv)
    if not args.path.endswith(".csv"):
        print(f"error: {args.path} is not a .csv file")
        return 1
    print("ok")
    return 0


for argv in (["data.csv"], ["data.txt"]):
    print("exit status:", main(argv))

# ✅ Expected output:
# ok
# exit status: 0
# error: data.txt is not a .csv file
# exit status: 1

A message for whoever ran the program can go with the status:

# check.py
import sys


def main():
    path = sys.argv[1] if len(sys.argv) > 1 else ""
    if not path.endswith(".csv"):
        sys.exit(f"error: {path!r} is not a .csv file")
    print("ok")


if __name__ == "__main__":
    main()
python check.py data.txt

That prints error: 'data.txt' is not a .csv file on standard error and ends with status 1. This site's editor reports any SystemExit as an error, even sys.exit(0), which is why the examples here return the status instead.

argparse writes the help from your arguments

help= describes each argument, and argparse builds the help screen from them. python greet.py --help, or -h, prints it and stops with status 0. This example prints the same text with format_help():

import argparse

parser = argparse.ArgumentParser(prog="greet", description="Say hello.")
parser.add_argument("name", help="who to greet")
parser.add_argument("--times", type=int, default=1, help="how many times")
parser.add_argument("--loud", action="store_true", help="shout")

print(parser.format_help(), end="")

# ✅ Expected output:
# usage: greet [-h] [--times TIMES] [--loud] name
#
# Say hello.
#
# positional arguments:
#   name           who to greet
#
# options:
#   -h, --help     show this help message and exit
#   --times TIMES  how many times
#   --loud         shout

In a help text, %(default)s becomes the option's default, and an option with choices shows them in braces:

import argparse

parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("--times", type=int, default=1, help="how many times (default: %(default)s)")
parser.add_argument("--speed", choices=["slow", "fast"], default="slow")

print(parser.format_help(), end="")

# ✅ Expected output:
# usage: greet [-h] [--times TIMES] [--speed {slow,fast}]
#
# options:
#   -h, --help           show this help message and exit
#   --times TIMES        how many times (default: 1)
#   --speed {slow,fast}

Python 3.10–3.14 head that section options:. Older tutorials show optional arguments:, from earlier versions. In a narrow terminal the lines wrap, and in a terminal Python 3.14 shows the help in colour. 3.13 also changed how an option with a short and a long name is listed: -t, --times TIMES, where earlier versions print -t TIMES, --times TIMES.

Subcommands: a parser for each command

Many tools take a command first, such as pip install and pip list. add_subparsers() gives each command a parser of its own, and set_defaults(handler=...) stores a function with it, so no if chain on the first word is needed. Higher-Order Functions & Function Factories kept functions as values in the same way.

import argparse


def add(args):
    print("adding", args.text)


def show(args):
    print("showing all tasks")


parser = argparse.ArgumentParser(prog="todo")
sub = parser.add_subparsers(dest="command", required=True)
add_parser = sub.add_parser("add", help="add a task")
add_parser.add_argument("text")
add_parser.set_defaults(handler=add)
sub.add_parser("list", help="show the tasks").set_defaults(handler=show)

for argv in (["add", "buy milk"], ["list"]):
    args = parser.parse_args(argv)
    print(args.command, end=": ")
    args.handler(args)

# ✅ Expected output:
# add: adding buy milk
# list: showing all tasks

dest="command" records which command was chosen, and required=True makes one compulsory. Each command checks its own arguments:

import argparse
import contextlib
import io


def error_of(parser, argv):
    stderr = io.StringIO()
    try:
        with contextlib.redirect_stderr(stderr):
            parser.parse_args(argv)
    except SystemExit as stop:
        return f"exit status {stop.code}: {stderr.getvalue().splitlines()[-1]}"
    return "no error"


parser = argparse.ArgumentParser(prog="todo")
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("add").add_argument("text")
sub.add_parser("list")

print(error_of(parser, []))
print(error_of(parser, ["add"]))

# ✅ Expected output:
# exit status 2: todo: error: the following arguments are required: command
# exit status 2: todo add: error: the following arguments are required: text

Without required=True, a command line with no command parses to Namespace(command=None), with no handler to call. A mistyped command stops with invalid choice, worded per version as for choices above. The main help lists the commands:

import argparse

parser = argparse.ArgumentParser(prog="todo")
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("add", help="add a task").add_argument("text")
sub.add_parser("list", help="show the tasks")

print(parser.format_help(), end="")

# ✅ Expected output:
# usage: todo [-h] {add,list} ...
#
# positional arguments:
#   {add,list}
#     add       add a task
#     list      show the tasks
#
# options:
#   -h, --help  show this help message and exit

Typer builds the same command line from a function's signature

Type Hints & Static Typing with mypy said Python doesn't check type hints while a program runs, but libraries can use them. Typer, a package from PyPI, is one: it reads a function's parameters and builds the command line from them. Here are its rules, shown with inspect.signature(), which Advanced Functions & Parameters Masterclass used. inspect.Parameter.empty is what a parameter with no default has as its default, and Introspection with inspect covers the rest.

import inspect


def greet(name: str, times: int = 1, loud: bool = False, dry_run: bool = False):
    pass


for param in inspect.signature(greet).parameters.values():
    option = "--" + param.name.replace("_", "-")
    if param.default is inspect.Parameter.empty:
        print(param.name, "is an argument of type", param.annotation.__name__)
    elif param.annotation is bool:
        print(param.name, "is a flag:", option, "or", "--no-" + option[2:])
    else:
        print(param.name, "is an option:", option, param.annotation.__name__, "default", param.default)

# ✅ Expected output:
# name is an argument of type str
# times is an option: --times int default 1
# loud is a flag: --loud or --no-loud
# dry_run is a flag: --dry-run or --no-dry-run

A parameter without a default is an argument, one with a default an option, a bool one a pair of flags, and underscores become dashes. Typer 0.27.3's own list of parameters for this function says the same. Those rules take a few lines of argparse, too; **vars(args) passes the Namespace's values as keyword arguments:

import argparse
import inspect


def greet(name: str, times: int = 1, loud: bool = False):
    for _ in range(times):
        message = f"Hello, {name}!"
        print(message.upper() if loud else message)


def parser_for(func):
    parser = argparse.ArgumentParser(prog=func.__name__)
    for param in inspect.signature(func).parameters.values():
        if param.default is inspect.Parameter.empty:
            parser.add_argument(param.name, type=param.annotation)
        elif param.annotation is bool:
            parser.add_argument("--" + param.name, action="store_true")
        else:
            parser.add_argument("--" + param.name, type=param.annotation, default=param.default)
    return parser


parser = parser_for(greet)
print(parser.format_usage(), end="")
args = parser.parse_args(["Ada", "--times", "2", "--loud"])
greet(**vars(args))

# ✅ Expected output:
# usage: greet [-h] [--times TIMES] [--loud] name
# HELLO, ADA!
# HELLO, ADA!

The greet program in Typer:

# greet.py
import typer


def main(name: str, times: int = 1, loud: bool = False):
    """Say hello to NAME."""
    for _ in range(times):
        message = f"Hello, {name}!"
        print(message.upper() if loud else message)


if __name__ == "__main__":
    typer.run(main)
python -m pip install typer
python greet.py Ada --times 2 --loud
python greet.py Ada --times two
python greet.py --help

Typer isn't part of Python, so it's installed with pip, best into a project's own environment as Virtual Environments & Dependency Management Best Practices shows. Typer 0.27.3 needs Python 3.10 or later and installs Rich, which draws its boxes, with it. The typer[all] some guides install names an extra that 0.27.3 doesn't have.

The second command prints HELLO, ADA! twice. The third stops with exit status 2: after Usage: greet.py [OPTIONS] {name} and Try 'greet.py --help' for help., a box on standard error says Invalid value for '--times': 'two' is not a valid int. Leaving the name out gives Missing argument 'name'., also with status 2. --help prints a boxed screen with the docstring, the argument name marked [required], and the options --times, marked [default: 1], and --loud/--no-loud.

With several commands, a program makes app = typer.Typer() and marks each function with @app.command(); python tool.py greet Ada then calls greet. A mistyped command gets a suggestion, No such command 'greeet'. Did you mean 'greet'?, with status 2. With only one command, its name isn't typed: python hello.py Boopie. raise typer.Exit(code=1) ends a Typer program with status 1.

A Typer app is tested by calling it with a list, through Typer's CliRunner:

import typer
from typer.testing import CliRunner

app = typer.Typer()


@app.command()
def greet(name: str, times: int = 1, loud: bool = False):
    for _ in range(times):
        message = f"Hello, {name}!"
        print(message.upper() if loud else message)


result = CliRunner().invoke(app, ["Ada", "--times", "2", "--loud"])
print(result.exit_code)
print(result.output, end="")

That prints 0 and two HELLO, ADA! lines; with ["Ada", "--times", "two"] the exit code is 2. This site's editor can't run any of these, since it has no Typer: their output above is from Typer 0.27.3 on Python 3.10–3.14.

Reading what's piped in

A program can also read standard input, which a terminal fills from a pipe, the output of one command sent into another. This one counts the lines of the files it's given, or of its standard input when it's given none:

# count.py
import argparse
import sys


def main(argv=None):
    parser = argparse.ArgumentParser(description="Count lines.")
    parser.add_argument("files", nargs="*", help="files to read (default: standard input)")
    args = parser.parse_args(argv)
    if not args.files:
        print(len(sys.stdin.readlines()))
        return 0
    for name in args.files:
        with open(name, encoding="utf-8") as f:
            print(name, len(f.readlines()))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
printf 'a\nb\n' | python count.py

That prints 2. This site's editor has no pipe to read from, so code that counts is better off taking the stream as a parameter: the program passes it sys.stdin, and a test, or this page, an io.StringIO. Working with Files, Streams & Large Datasets handles streams too large to read at once.

import io


def count_lines(stream):
    return len(stream.readlines())


print(count_lines(io.StringIO("one\ntwo\nthree\n")))

# ✅ Expected output:
# 3

Practice: finish the tally parser

Fill in the three blanks so the parser takes words, a --min length as a number and an --upper flag, then parses the list. The hints under the code give each word.

import argparse

parser = argparse.ArgumentParser(prog="tally", description="Count words.")
parser.add_argument("words", nargs="+", help="the words to count")
parser.add_argument("--min", ___=int, default=1, help="shortest word to count")
parser.add_argument("--upper", action="___", help="show the words in capitals")

args = parser.___(["tea", "is", "hot", "--min", "3", "--upper"])
kept = [word for word in args.words if len(word) >= args.min]
if args.upper:
    kept = [word.upper() for word in kept]
print(args)
print(len(kept), "words:", kept)

# 👉 replace ___ with type
# 👉 replace ___ with store_true
# 👉 replace ___ with parse_args



# ✅ Expected output:
# Namespace(words=['tea', 'is', 'hot'], min=3, upper=True)
# 2 words: ['TEA', 'HOT']

On your own: a notes program with two commands

Write a parser for a notes program with two subcommands: add TEXT adds a note to a list, and count prints how many notes there are. Store each subcommand's function with set_defaults. Parse ["add", "buy milk"], ["add", "call Ada"] and ["count"] in turn, and call the function each time.

import argparse

notes = []


def add(args):
    notes.append(args.text)
    print("added:", args.text)


def count(args):
    print(len(notes), "notes")


parser = argparse.ArgumentParser(prog="notes")
sub = parser.add_subparsers(dest="command", required=True)
add_parser = sub.add_parser("add", help="add a note")
add_parser.add_argument("text")
add_parser.set_defaults(handler=add)
sub.add_parser("count", help="count the notes").set_defaults(handler=count)

for argv in (["add", "buy milk"], ["add", "call Ada"], ["count"]):
    args = parser.parse_args(argv)
    args.handler(args)

# ✅ Expected output:
# added: buy milk
# added: call Ada
# 2 notes

Practice quiz

Positionals a and b have no type=. parse_args(["2", "3"]), then print(args.a + args.b). What prints?

  • 5
  • 23
  • TypeError
  • ('2', '3')

Answer: 23. Without type=, every value stays the text it was typed as, and + joins two strings.

--debug is declared with type=bool. What is parse_args(["--debug", "False"]).debug?

  • True
  • False
  • 'False'
  • It stops with an error

Answer: True. type= is called on the text, and bool() of any text but "" is True. A flag needs action="store_true".

parser.add_argument("--dry-run", action="store_true"), then vars(parser.parse_args(["--dry-run"])). What prints?

  • {'dry-run': True}
  • {'dry_run': True}
  • {'dryrun': True}
  • {'--dry-run': True}

Answer: {'dry_run': True}. An option's dashes become underscores in the Namespace, so the value is read as args.dry_run.

parser.add_argument("-v", "--verbose", action="count") with no default. What is parse_args([]).verbose?

  • 0
  • False
  • None
  • It stops with an error

Answer: None. An option that isn't given gets its default, and count's default is None unless you set default=0.

--times has type=int. try: parser.parse_args(["--times", "two"]) except Exception: print("caught"), then print("carried on"). What prints?

  • caught, then carried on
  • carried on
  • Nothing: the program stops with exit status 2
  • caught

Answer: Nothing: the program stops with exit status 2. argparse stops the program with SystemExit, which isn't an Exception, so except Exception lets it through. Its usage and error lines go to standard error, not standard output.

greet.py needs a name, and you run python greet.py with none. What exit status does the shell get?

  • 0
  • 1
  • 127
  • 2

Answer: 2. argparse prints the usage and the error on standard error and stops with status 2, its status for a wrong command line.

sub = parser.add_subparsers(dest="command") with one subcommand, list. What does parse_args([]) give?

  • An error: the following arguments are required: command
  • Namespace()
  • Namespace(command='list')
  • Namespace(command=None)

Answer: Namespace(command=None). Without required=True a subcommand may be left out, and dest then holds None. It takes required=True to make argparse ask for one.

hello.py is a Typer app with one @app.command(), def greet(name: str). Which command prints Hello Boopie!?

  • python hello.py Boopie
  • python hello.py greet Boopie
  • python hello.py --name Boopie
  • python hello.py greet --name Boopie

Answer: python hello.py Boopie. With a single command, Typer runs it without its name. In python hello.py greet Boopie, greet is taken as the name and Boopie is one argument too many: Typer stops with Got unexpected extra argument(s) (Boopie).

Continue this course

Frequently asked questions

How do I see a command's exit status?

In bash and zsh, echo $? straight after the command prints it. PowerShell keeps it in $LASTEXITCODE, and Command Prompt in %ERRORLEVEL%. Running Commands with subprocess reads it from Python, as returncode.

Can argparse read arguments from a file?

Yes: ArgumentParser(fromfile_prefix_chars="@") makes an argument @args.txt stand for the lines of args.txt, one argument per line. A file holding Ada, --times and 2 on three lines parses as Namespace(name='Ada', times=2).

Why is my help in colour?

From Python 3.14, argparse colours its help and usage in a terminal. NO_COLOR=1 in the environment turns that off, and so does ArgumentParser(color=False), which earlier versions don't accept. Help sent into a pipe or a file has no colour unless FORCE_COLOR is set.

Why does the usage line say __main__.py?

Without prog=, argparse names the program after the file that started it. Run as python -m tally, that's the package's __main__.py on Python 3.10 to 3.13, while 3.14 builds it from the command, such as python3.14 -m tally. Module & Package Architecture for Large Codebases covers -m and __main__.py; pass prog= to choose the name yourself.

What about argparse.FileType?

Python 3.14 issues a PendingDeprecationWarning when one is created: FileType is deprecated. Simply open files after parsing arguments. Warnings of that kind are hidden by default, as The warnings Module explains. Take the path as text and open it yourself, with open() in a with block, after parse_args().

This site's editor shows SystemExit: 0 for a script that works. Why?

The editor reports any SystemExit as an error, even sys.exit(0), which in a terminal is a normal end with status 0. That's why the examples here return the status from main() instead of calling sys.exit().

How do I make my tool a command I can type anywhere?

With an entry point in the project's pyproject.toml, under [project.scripts]: installing the project then makes a command that calls your main() and passes its return value to sys.exit(). Packaging & Publishing Python Libraries to PyPI shows how.

Typer or Click?

Typer is built on Click's way of working: Typer 0.27.3 includes code taken and adapted from Click, so it doesn't install Click itself. Click has you declare each option with a decorator; Typer reads them from the function's parameters. This site's editor loads Click when a program imports it, but not Typer.

Related lessons