CLIs with argparse
argparse is the standard library's command-line parser. In a dozen lines it gives a script typed options,
defaults, validation, --help generated from the definitions, subcommands, and error messages with exit status 2.
It is the main reason a Python script feels like a real tool where the Bash version needed a hand-written while
loop (Arguments, Usage and Exit Codes).
Options, types and defaults
parse_args() reads sys.argv; passing a list instead is how you test a parser, and how the browser examples run:
import argparse
import os
def build_parser():
p = argparse.ArgumentParser(prog="deployctl", description="Deploy a service to an environment.")
p.add_argument("service", help="service name, e.g. shop-api")
p.add_argument("-e", "--env", choices=["dev", "staging", "prod"], default="dev",
help="target environment (default: %(default)s)")
p.add_argument("-r", "--replicas", type=int, default=2, metavar="N")
p.add_argument("--image-tag", default=os.environ.get("IMAGE_TAG", "latest"),
help="image tag (default: $IMAGE_TAG or latest)")
p.add_argument("-n", "--dry-run", action="store_true", help="print the plan, change nothing")
p.add_argument("-v", "--verbose", action="count", default=0, help="-v, -vv for more output")
p.add_argument("--label", action="append", default=[], metavar="KEY=VALUE", help="repeatable")
return p
parser = build_parser()
for argv in (["shop-api"],
["shop-api", "-e", "prod", "--replicas", "6", "-n", "-vv", "--label", "team=core", "--label", "tier=api"],
["shop-api", "--env=staging", "--image-tag", "1.4.2"]):
args = parser.parse_args(argv)
print(vars(args)){'service': 'shop-api', 'env': 'dev', 'replicas': 2, 'image_tag': 'latest', 'dry_run': False, 'verbose': 0, 'label': []}
{'service': 'shop-api', 'env': 'prod', 'replicas': 6, 'image_tag': 'latest', 'dry_run': True, 'verbose': 2, 'label': ['team=core', 'tier=api']}
{'service': 'shop-api', 'env': 'staging', 'replicas': 2, 'image_tag': '1.4.2', 'dry_run': False, 'verbose': 0, 'label': []}
type=intconverts and validates:--replicas sixis rejected with a message.choiceslimits a value to a fixed set and lists the set in the help and in the error.action="store_true"makes a flag;"count"counts repeats (-vv= 2);"append"collects a repeatable option into a list.- Long options become attribute names with dashes turned into underscores:
--image-tag→args.image_tag. - The same precedence as in Bash: the flag wins over the environment (
IMAGE_TAG), which wins over the built-in default.
Help and errors, for real
The parser writes --help to stdout and exits 0; on a bad argument it prints the usage and the error to stderr and
exits with status 2. Here is the same parser as a real script:
cat > deployctl <<'PY'
#!/usr/bin/env python3
import argparse
import sys
def main(argv=None):
p = argparse.ArgumentParser(prog="deployctl", description="Deploy a service to an environment.")
p.add_argument("service", help="service name, e.g. shop-api")
p.add_argument("-e", "--env", choices=["dev", "staging", "prod"], default="dev",
help="target environment (default: %(default)s)")
p.add_argument("-r", "--replicas", type=int, default=2, metavar="N")
p.add_argument("-n", "--dry-run", action="store_true", help="print the plan, change nothing")
args = p.parse_args(argv)
if args.env == "prod" and args.replicas < 2:
p.error("prod needs at least 2 replicas") # same format and status as built-in errors
verb = "would deploy" if args.dry_run else "deploying"
print(f"{verb} {args.service} to {args.env} with {args.replicas} replica(s)")
return 0
if __name__ == "__main__":
sys.exit(main())
PY
chmod +x deployctl
COLUMNS=80 ./deployctl --help; echo "-> status $?"
./deployctl shop-api -e prod -n; echo "-> status $?"
./deployctl shop-api --env production; echo "-> status $?"
./deployctl shop-api --replicas six; echo "-> status $?"
./deployctl shop-api -e prod -r 1; echo "-> status $?"
./deployctl; echo "-> status $?"usage: deployctl [-h] [-e {dev,staging,prod}] [-r N] [-n] service
Deploy a service to an environment.
positional arguments:
service service name, e.g. shop-api
options:
-h, --help show this help message and exit
-e {dev,staging,prod}, --env {dev,staging,prod}
target environment (default: dev)
-r N, --replicas N
-n, --dry-run print the plan, change nothing
-> status 0
would deploy shop-api to prod with 2 replica(s)
-> status 0
usage: deployctl [-h] [-e {dev,staging,prod}] [-r N] [-n] service
deployctl: error: argument -e/--env: invalid choice: 'production' (choose from 'dev', 'staging', 'prod')
-> status 2
usage: deployctl [-h] [-e {dev,staging,prod}] [-r N] [-n] service
deployctl: error: argument -r/--replicas: invalid int value: 'six'
-> status 2
usage: deployctl [-h] [-e {dev,staging,prod}] [-r N] [-n] service
deployctl: error: prod needs at least 2 replicas
-> status 2
usage: deployctl [-h] [-e {dev,staging,prod}] [-r N] [-n] service
deployctl: error: the following arguments are required: service
-> status 2
parser.error() is the right way to report a combination of arguments that is invalid: the user gets the same
format and the same status as for any other usage error. COLUMNS=80 pins the help's line width, which otherwise
follows the terminal.
Subcommands
Tools like git, kubectl and aws group actions as subcommands. add_subparsers does the same; set_defaults(func=…)
attaches the function that handles each one:
import argparse
def cmd_list(args):
envs = ["dev", "staging", "prod"]
for e in envs if args.all else envs[:1]:
print(f"env {e}")
return 0
def cmd_scale(args):
print(f"scale {args.service} in {args.env} to {args.replicas}")
return 0
def build_parser():
p = argparse.ArgumentParser(prog="opsctl")
p.add_argument("--env", default="dev") # a global option, before the subcommand
sub = p.add_subparsers(dest="command", required=True, metavar="COMMAND")
ls = sub.add_parser("list", help="list environments")
ls.add_argument("-a", "--all", action="store_true")
ls.set_defaults(func=cmd_list)
sc = sub.add_parser("scale", help="change the replica count")
sc.add_argument("service")
sc.add_argument("replicas", type=int)
sc.set_defaults(func=cmd_scale)
return p
def main(argv):
args = build_parser().parse_args(argv)
return args.func(args)
print("->", main(["list"]))
print("->", main(["list", "--all"]))
print("->", main(["--env", "prod", "scale", "shop-api", "6"]))env dev
-> 0
env dev
env staging
env prod
-> 0
scale shop-api in prod to 6
-> 0
Beyond argparse
For larger tools, Click and Typer (Typer builds on Click and reads options from type hints) give nicer help,
nested command groups, prompts and shell completion. They are third-party packages, so they make sense for tools you
install (with pipx/uv tool), less for scripts copied to servers. The Toolkit lists them.
import typer
app = typer.Typer()
@app.command()
def scale(service: str, replicas: int, env: str = "dev", dry_run: bool = False):
"""Change the replica count of SERVICE."""
...
if __name__ == "__main__":
app()Test yourself
What does argparse do when --replicas six is passed to an option with type=int?
- Stores the string "six"
- Stores 0
- Prints a usage error to stderr and exits with status 2
- Raises an uncaught ValueError with a traceback
Which attribute holds the value of --image-tag?
- args.image-tag
- args.imageTag
- args.image_tag
- args['image-tag']
How should a script report that --env prod with --replicas 1 is not allowed?
- print() and return 0
- raise ValueError
- parser.error("prod needs at least 2 replicas")
- sys.exit("error")