Path: blob/master/examples/cli/argparse_class.py
305 views
# source = https://chase-seibert.github.io/blog/2014/03/21/python-multilevel-argparse.html1# archive = https://web.archive.org/web/20220206210318/https://chase-seibert.github.io/blog/2014/03/21/python-multilevel-argparse.html2import argparse3import sys456class FakeGit:7def __init__(self):8parser = argparse.ArgumentParser(9description="Pretends to be git",10usage="""git <command> [<args>]1112The most commonly used git commands are:13commit Record changes to the repository14fetch Download objects and refs from another repository15""",16)17parser.add_argument("command", help="Subcommand to run")18args = parser.parse_args(sys.argv[1:2])19if not hasattr(self, args.command):20print("Unrecognized command")21parser.print_help()22sys.exit(1)23getattr(self, args.command)() # dispatch pattern2425def commit(self):26parser = argparse.ArgumentParser(description="Record changes to the repository")27parser.add_argument("--amend", action="store_true")28args = parser.parse_args(sys.argv[2:])29print(f"Running git commit, amend={args.amend}")3031def fetch(self):32parser = argparse.ArgumentParser(33description="Download objects and refs from another repository"34)35parser.add_argument("repository")36args = parser.parse_args(sys.argv[2:])37print(f"Running git fetch, repository={args.repository}")383940if __name__ == "__main__":41FakeGit()424344