Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

How do you build subcommands with `argparse`?

IntermediateConceptOS, filesystem, subprocess & CLIs
Answer
p = argparse.ArgumentParser(prog="ops")
sub = p.add_subparsers(dest="command", required=True)

s = sub.add_parser("snapshot", help="snapshot volumes")
s.add_argument("--volume-id", required=True)
s.set_defaults(func=cmd_snapshot)

c = sub.add_parser("cleanup", help="delete old snapshots")
c.add_argument("--older-than", type=int, default=30)
c.set_defaults(func=cmd_cleanup)

args = p.parse_args()
sys.exit(args.func(args))

set_defaults(func=...) is the standard dispatch trick; each handler returns an exit code.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs