Skip to content

Commit f5b1d66

Browse files
committed
Simplify subcommand example within argparse_example.py
The original example was overly complicated. This replaces it with a much simpler one that is easier to digest and understand. Also switched to using the `cmd2.as_subcommand_to` decorator.
1 parent 61273d6 commit f5b1d66

File tree

1 file changed

+35
-88
lines changed

1 file changed

+35
-88
lines changed

examples/argparse_example.py

Lines changed: 35 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -106,98 +106,45 @@ def do_print_unknown(self, args: argparse.Namespace, unknown: list[str]) -> None
106106

107107
## ------ Examples demonstrating how to use argparse subcommands -----
108108

109-
sport_item_strs = ('Bat', 'Basket', 'Basketball', 'Football', 'Space Ball')
110-
111109
# create the top-level parser for the base command
112-
base_parser = cmd2.Cmd2ArgumentParser()
113-
base_subparsers = base_parser.add_subparsers(title='subcommands', help='subcommand help')
114-
115-
# create the parser for the "foo" subcommand
116-
parser_foo = base_subparsers.add_parser('foo', help='foo help')
117-
parser_foo.add_argument('-x', type=int, default=1, help='integer')
118-
parser_foo.add_argument('y', type=float, help='float')
119-
parser_foo.add_argument('input_file', type=str, help='Input File')
120-
121-
# create the parser for the "bar" subcommand
122-
parser_bar = base_subparsers.add_parser('bar', help='bar help')
123-
124-
bar_subparsers = parser_bar.add_subparsers(title='layer3', help='help for 3rd layer of commands')
125-
parser_bar.add_argument('z', help='string')
126-
127-
bar_subparsers.add_parser('apple', help='apple help')
128-
bar_subparsers.add_parser('artichoke', help='artichoke help')
129-
bar_subparsers.add_parser('cranberries', help='cranberries help')
130-
131-
# create the parser for the "sport" subcommand
132-
parser_sport = base_subparsers.add_parser('sport', help='sport help')
133-
sport_arg = parser_sport.add_argument('sport', help='Enter name of a sport', choices=sport_item_strs)
134-
135-
# create the top-level parser for the alternate command
136-
# The alternate command doesn't provide its own help flag
137-
base2_parser = cmd2.Cmd2ArgumentParser(add_help=False)
138-
base2_subparsers = base2_parser.add_subparsers(title='subcommands', help='subcommand help')
139-
140-
# create the parser for the "foo" subcommand
141-
parser_foo2 = base2_subparsers.add_parser('foo', help='foo help')
142-
parser_foo2.add_argument('-x', type=int, default=1, help='integer')
143-
parser_foo2.add_argument('y', type=float, help='float')
144-
parser_foo2.add_argument('input_file', type=str, help='Input File')
145-
146-
# create the parser for the "bar" subcommand
147-
parser_bar2 = base2_subparsers.add_parser('bar', help='bar help')
148-
149-
bar2_subparsers = parser_bar2.add_subparsers(title='layer3', help='help for 3rd layer of commands')
150-
parser_bar2.add_argument('z', help='string')
151-
152-
bar2_subparsers.add_parser('apple', help='apple help')
153-
bar2_subparsers.add_parser('artichoke', help='artichoke help')
154-
bar2_subparsers.add_parser('cranberries', help='cranberries help')
155-
156-
# create the parser for the "sport" subcommand
157-
parser_sport2 = base2_subparsers.add_parser('sport', help='sport help')
158-
sport2_arg = parser_sport2.add_argument('sport', help='Enter name of a sport', choices=sport_item_strs)
159-
160-
# subcommand functions for the base command
161-
def base_foo(self, args: argparse.Namespace) -> None:
162-
"""Foo subcommand of base command."""
163-
self.poutput(args.x * args.y)
164-
165-
def base_bar(self, args: argparse.Namespace) -> None:
166-
"""Bar subcommand of base command."""
167-
self.poutput(f'(({args.z}))')
168-
169-
def base_sport(self, args: argparse.Namespace) -> None:
170-
"""Sport subcommand of base command."""
171-
self.poutput(f'Sport is {args.sport}')
172-
173-
# Set handler functions for the subcommands
174-
parser_foo.set_defaults(func=base_foo)
175-
parser_bar.set_defaults(func=base_bar)
176-
parser_sport.set_defaults(func=base_sport)
177-
178-
@cmd2.with_argparser(base_parser)
179-
@cmd2.with_category(ARGPARSE_SUBCOMMANDS)
180-
def do_base(self, args: argparse.Namespace) -> None:
181-
"""Base command help."""
182-
func = getattr(args, 'func', None)
183-
if func is not None:
184-
# Call whatever subcommand function was selected
185-
func(self, args)
186-
else:
187-
# No subcommand was provided, so call help
188-
self.do_help('base')
189-
190-
@cmd2.with_argparser(base2_parser)
110+
calculate_parser = cmd2.Cmd2ArgumentParser(description="Perform simple mathematical calculations.")
111+
calculate_subparsers = calculate_parser.add_subparsers(title='operation', help='Available operations')
112+
113+
# create the parser for the "add" subcommand
114+
add_description = "Add two numbers"
115+
add_parser = cmd2.Cmd2ArgumentParser("add", description=add_description)
116+
add_parser.add_argument('num1', type=int, help='The first number')
117+
add_parser.add_argument('num2', type=int, help='The second number')
118+
119+
# create the parser for the "add" subcommand
120+
subtract_description = "Subtract two numbers"
121+
subtract_parser = cmd2.Cmd2ArgumentParser("subtract", description=subtract_description)
122+
subtract_parser.add_argument('num1', type=int, help='The first number')
123+
subtract_parser.add_argument('num2', type=int, help='The second number')
124+
125+
# subcommand functions for the calculate command
126+
@cmd2.as_subcommand_to('calculate', 'add', add_parser, help=add_description.lower())
127+
def add(self, args: argparse.Namespace) -> None:
128+
"""add subcommand of calculate command."""
129+
result = args.num1 + args.num2
130+
self.poutput(f"{args.num1} + {args.num2} = {result}")
131+
132+
@cmd2.as_subcommand_to('calculate', 'subtract', subtract_parser, help=subtract_description.lower())
133+
def subtract(self, args: argparse.Namespace) -> None:
134+
"""subtract subcommand of calculate command."""
135+
result = args.num1 - args.num2
136+
self.poutput(f"{args.num1} - {args.num2} = {result}")
137+
138+
@cmd2.with_argparser(calculate_parser)
191139
@cmd2.with_category(ARGPARSE_SUBCOMMANDS)
192-
def do_alternate(self, args: argparse.Namespace) -> None:
193-
"""Alternate command help."""
194-
func = getattr(args, 'func', None)
195-
if func is not None:
196-
# Call whatever subcommand function was selected
197-
func(self, args)
140+
def do_calculate(self, ns: argparse.Namespace) -> None:
141+
"""Calculate a simple mathematical operation on two integers."""
142+
handler = ns.cmd2_handler.get()
143+
if handler is not None:
144+
handler(ns)
198145
else:
199146
# No subcommand was provided, so call help
200-
self.do_help('alternate')
147+
self.do_help('calculate')
201148

202149

203150
if __name__ == '__main__':

0 commit comments

Comments
 (0)