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.
More on OS, filesystem, subprocess & CLIs
`os.path` vs `pathlib`: which do you use and why?BeginnerHow do you read environment variables safely?BeginnerHow do you walk a directory tree and find files?BeginnerWhat does `shutil` give you that `os` does not?BeginnerHow do you run an external command correctly with `subprocess`?BeginnerWhy is `shell=True` dangerous, and when is it acceptable?Intermediate