Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gmolveau
GitHub Repository: gmolveau/python_full_course
Path: blob/master/examples/cli/argparse_class.py
305 views
1
# source = https://chase-seibert.github.io/blog/2014/03/21/python-multilevel-argparse.html
2
# archive = https://web.archive.org/web/20220206210318/https://chase-seibert.github.io/blog/2014/03/21/python-multilevel-argparse.html
3
import argparse
4
import sys
5
6
7
class FakeGit:
8
def __init__(self):
9
parser = argparse.ArgumentParser(
10
description="Pretends to be git",
11
usage="""git <command> [<args>]
12
13
The most commonly used git commands are:
14
commit Record changes to the repository
15
fetch Download objects and refs from another repository
16
""",
17
)
18
parser.add_argument("command", help="Subcommand to run")
19
args = parser.parse_args(sys.argv[1:2])
20
if not hasattr(self, args.command):
21
print("Unrecognized command")
22
parser.print_help()
23
sys.exit(1)
24
getattr(self, args.command)() # dispatch pattern
25
26
def commit(self):
27
parser = argparse.ArgumentParser(description="Record changes to the repository")
28
parser.add_argument("--amend", action="store_true")
29
args = parser.parse_args(sys.argv[2:])
30
print(f"Running git commit, amend={args.amend}")
31
32
def fetch(self):
33
parser = argparse.ArgumentParser(
34
description="Download objects and refs from another repository"
35
)
36
parser.add_argument("repository")
37
args = parser.parse_args(sys.argv[2:])
38
print(f"Running git fetch, repository={args.repository}")
39
40
41
if __name__ == "__main__":
42
FakeGit()
43
44