diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py index 44f64ee1c..1b1efce7e 100644 --- a/cmd2/argparse_completer.py +++ b/cmd2/argparse_completer.py @@ -10,6 +10,7 @@ deque, ) from typing import ( + IO, TYPE_CHECKING, Optional, Union, @@ -624,24 +625,28 @@ def complete_subcommand_help(self, text: str, line: str, begidx: int, endidx: in break return [] - def format_help(self, tokens: list[str]) -> str: - """Supports cmd2's help command in the retrieval of help text. + def print_help(self, tokens: list[str], file: Optional[IO[str]] = None) -> None: + """Supports cmd2's help command in the printing of help text. :param tokens: arguments passed to help command - :return: help text of the command being queried. + :param file: optional file object where the argparse should write help text + If not supplied, argparse will write to sys.stdout. """ - # If our parser has subcommands, we must examine the tokens and check if they are subcommands + # If our parser has subcommands, we must examine the tokens and check if they are subcommands. # If so, we will let the subcommand's parser handle the rest of the tokens via another ArgparseCompleter. - if self._subcommand_action is not None: - for token_index, token in enumerate(tokens): - if token in self._subcommand_action.choices: - parser: argparse.ArgumentParser = self._subcommand_action.choices[token] - completer_type = self._cmd2_app._determine_ap_completer_type(parser) + if tokens and self._subcommand_action is not None: + parser = cast( + Optional[argparse.ArgumentParser], + self._subcommand_action.choices.get(tokens[0]), + ) - completer = completer_type(parser, self._cmd2_app) - return completer.format_help(tokens[token_index + 1 :]) - break - return self._parser.format_help() + if parser: + completer_type = self._cmd2_app._determine_ap_completer_type(parser) + completer = completer_type(parser, self._cmd2_app) + completer.print_help(tokens[1:]) + return + + self._parser.print_help(file=file) def _complete_arg( self, diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 387b0df35..d9bc4abc6 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -3876,9 +3876,7 @@ def do_help(self, args: argparse.Namespace) -> None: # If the command function uses argparse, then use argparse's help if func is not None and argparser is not None: completer = argparse_completer.DEFAULT_AP_COMPLETER(argparser, self) - - # Set end to blank so the help output matches how it looks when "command -h" is used - self.poutput(completer.format_help(args.subcommands), end='') + completer.print_help(args.subcommands, self.stdout) # If there is a help func delegate to do_help elif help_func is not None: