Building a Python CLI with nested subcommands and autocompletion
A command-line tool can begin as a small script and quickly become a proper interface. My first version handled a couple of flags, but as features accumulated, a flat collection of options became difficult to explain and maintain. The natural next step was a command structure that grouped related operations under clear subcommands.
Python’s argparse module provided the foundation. With nested parsers, reusable options, dispatch functions and shell completion, I could build a CLI that felt predictable without adding a large dependency. The result suited the sort of Linux utilities I use in open-source projects: scriptable, inspectable and friendly to people working in a terminal.
Designing the command tree
I started by describing the interface as a hierarchy rather than as a list of arguments. A hypothetical administration tool might expose commands such as server list, server inspect, and server ban. The first word selects a resource, while the second selects an action.
import argparse
def build_parser():
parser = argparse.ArgumentParser(
prog="guard",
description="Inspect and manage blocked hosts"
)
commands = parser.add_subparsers(
dest="command",
required=True
)
server = commands.add_parser("server", help="Manage servers")
server_commands = server.add_subparsers(
dest="server_command",
required=True
)
server_commands.add_parser("list", help="List configured servers")
inspect = server_commands.add_parser(
"inspect",
help="Show server details"
)
inspect.add_argument("name")
return parser
The dest values matter because they preserve the selected path in the parsed namespace. Setting required=True also prevents the CLI from silently doing nothing when a user types only guard or guard server. On older Python versions, where required subparsers were unavailable, I handled missing commands explicitly after parsing.
This arrangement reflects how people remember commands. Someone operating a small VPS in Sydney may think in terms of “server inspect web01”, while a developer in Perth may need “server ban address”. The syntax leaves room for additional resources without turning every option into a global flag.
Dispatching nested commands cleanly
Rather than writing a long chain of if statements, I attached a function to each leaf parser with set_defaults. This keeps parsing separate from application behaviour and makes each operation straightforward to test.
def list_servers(args):
print("web01")
print("worker01")
def inspect_server(args):
print(f"Details for {args.name}")
def build_parser():
parser = argparse.ArgumentParser(prog="guard")
commands = parser.add_subparsers(dest="command", required=True)
server = commands.add_parser("server")
server_commands = server.add_subparsers(
dest="server_command",
required=True
)
listing = server_commands.add_parser("list")
listing.set_defaults(func=list_servers)
inspect = server_commands.add_parser("inspect")
inspect.add_argument("name")
inspect.set_defaults(func=inspect_server)
return parser
args = build_parser().parse_args()
args.func(args)
Every valid leaf command receives a callable, so the entry point stays small. I can also inject services, configuration or a logger into those handlers instead of making them depend on global state. That is useful for open-source software, where contributors may run the same command under different Python environments.
For a production utility, I catch expected operational errors at the boundary and convert them into useful messages with a non-zero exit status. A missing configuration file should explain what is absent; a traceback should generally be reserved for a debug mode. Clear failures matter when commands run from cron, systemd timers or deployment scripts.
Sharing options across command levels
Nested CLIs often need options at different scopes. A global --config flag belongs on the root parser, while --format json might apply to every server operation. Action-specific values, such as a hostname, belong on the leaf parser.
I used parent parsers to avoid repeating common arguments:
common = argparse.ArgumentParser(add_help=False)
common.add_argument("--format", choices=("text", "json"), default="text")
server = commands.add_parser(
"server",
parents=[common]
)
The placement affects where users can put the option. If an option is registered only on server, then guard server --format json list works, while guard --format json server list does not. I documented one canonical form and tested the alternatives so the help output matched actual behaviour.
Australian operators often work across mixed environments: a Melbourne workstation, a Brisbane office server and a cloud region in Sydney can all have slightly different defaults. Explicit configuration flags and environment-variable support reduce surprises when a command moves between machines. I kept environment handling outside argparse, then used parser defaults so command-line values always took precedence.
Adding shell completion
Argparse parses completed input, but it does not generate completion scripts by itself. I used argcomplete, which integrates with an ArgumentParser and can offer subcommands, choices and dynamic values.
The entry point needs a small hook:
import argcomplete
parser = build_parser()
argcomplete.autocomplete(parser)
args = parser.parse_args()
args.func(args)
After enabling the shell integration, pressing Tab can complete server, inspect, output formats and other known values. For commands installed through a Python package, I included the completion setup in the installation instructions rather than assuming every user already had it configured.
Dynamic completion is useful for names fetched from a local configuration file, although it should remain fast. A completion function that contacts a remote API on every Tab press will feel sluggish, particularly on a residential NBN connection or a high-latency link to an overseas service. Cached values and simple filesystem completion are usually the better trade-off.
Testing the interface as a public API
I treat command syntax as an API. Renaming server inspect or changing an option’s meaning can break shell scripts even when the internal Python code remains compatible. I therefore test parser behaviour directly by passing argument lists to parse_args.
def parse(values):
return build_parser().parse_args(values)
args = parse(["server", "inspect", "web01"])
assert args.name == "web01"
assert args.server_command == "inspect"
I also test invalid commands, missing positional arguments, mutually exclusive options and exit codes. Help output deserves attention because it is often the first documentation a user sees. Short examples in each subparser make the interface easier to discover than a large block of abstract prose.
The same principle applies to project documentation and presentation. When reviewing examples of approachable developer tooling, I found useful inspiration in terminal UX ideas that favour clear language and visible affordances. That mindset helped me keep the command vocabulary plain: familiar verbs, consistent option names and no clever abbreviations.
A mature CLI should also report its version, honour standard output conventions and avoid mixing diagnostic messages with machine-readable results. Text can be pleasant for a person in a terminal; JSON or line-oriented output is better for pipelines. With that separation in place, a Python command-line application can grow from a handy script into a reliable tool without losing its Unix-friendly character.
