Skip to content

Commit d6a274c

Browse files
committed
Updated save_help_text.py example script.
1 parent 6f7ca85 commit d6a274c

1 file changed

Lines changed: 27 additions & 21 deletions

File tree

examples/scripts/save_help_text.py

Lines changed: 27 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,29 @@
22
This is meant to be run within a cmd2 session using run_pyscript.
33
"""
44

5-
import argparse
65
import os
76
import sys
87
from typing import TextIO
98

9+
from cmd2 import Cmd2ArgumentParser
10+
1011
ASTERISKS = "********************************************************"
1112

1213

13-
def get_sub_commands(parser: argparse.ArgumentParser) -> list[str]:
14-
"""Get a list of subcommands for an ArgumentParser."""
15-
sub_cmds = []
14+
def get_sub_commands(parser: Cmd2ArgumentParser) -> list[str]:
15+
"""Get a list of subcommands for a Cmd2ArgumentParser."""
16+
try:
17+
subparsers_action = parser._get_subparsers_action()
18+
except ValueError:
19+
# No subcommands
20+
return []
1621

17-
# Check if this is parser has subcommands
18-
if parser is not None and parser._subparsers is not None:
19-
# Find the _SubParsersAction for the subcommands of this parser
20-
for action in parser._subparsers._actions:
21-
if isinstance(action, argparse._SubParsersAction):
22-
for sub_cmd, sub_cmd_parser in action.choices.items():
23-
sub_cmds.append(sub_cmd)
22+
sub_cmds = []
23+
for subcmd, subcmd_parser in subparsers_action.choices.items():
24+
sub_cmds.append(subcmd)
2425

25-
# Look for nested subcommands
26-
sub_cmds.extend(f'{sub_cmd} {nested_sub_cmd}' for nested_sub_cmd in get_sub_commands(sub_cmd_parser))
27-
break
26+
# Look for nested subcommands
27+
sub_cmds.extend(f'{subcmd} {nested_subcmd}' for nested_subcmd in get_sub_commands(subcmd_parser))
2828

2929
sub_cmds.sort()
3030
return sub_cmds
@@ -60,8 +60,7 @@ def main() -> None:
6060
# Open the output file
6161
outfile_path = os.path.expanduser(sys.argv[1])
6262
try:
63-
with open(outfile_path, 'w') as outfile:
64-
pass
63+
outfile = open(outfile_path, 'w') # noqa: SIM115
6564
except OSError as e:
6665
print(f"Error opening {outfile_path} because: {e}")
6766
return
@@ -83,11 +82,18 @@ def main() -> None:
8382
is_command = item in all_commands
8483
add_help_to_file(item, outfile, is_command)
8584

86-
if is_command:
87-
# Add any subcommands
88-
for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)):
89-
full_cmd = f'{item} {subcmd}'
90-
add_help_to_file(full_cmd, outfile, is_command)
85+
if not is_command:
86+
continue
87+
88+
cmd_func = self.cmd_func(item)
89+
parser = self._command_parsers.get(cmd_func)
90+
if parser is None:
91+
continue
92+
93+
# Add any subcommands
94+
for subcmd in get_sub_commands(parser):
95+
full_cmd = f'{item} {subcmd}'
96+
add_help_to_file(full_cmd, outfile, is_command)
9197

9298
outfile.close()
9399
print(f"Output written to {outfile_path}")

0 commit comments

Comments
 (0)