MCPcopy Index your code
hub / github.com/python-cmd2/cmd2 / Cmd2ArgumentParser

Class Cmd2ArgumentParser

cmd2/argparse_utils.py:564–928  ·  view source on GitHub ↗

Custom ArgumentParser class that improves error and help output.

Source from the content-addressed store, hash-verified

562
563
564class Cmd2ArgumentParser(argparse.ArgumentParser):
565 """Custom ArgumentParser class that improves error and help output."""
566
567 # Thread-local storage shared by all parser instances (including subparsers)
568 _thread_locals: ClassVar[_ParserThreadLocals] = _ParserThreadLocals()
569
570 @contextlib.contextmanager
571 def output_to(self, file: IO[str] | None) -> Iterator[None]:
572 """Context manager to temporarily set the output stream during argparse operations.
573
574 This is helpful for directing output for functions like `parse_args()`, which
575 default to `sys.stdout` and lack a `file` argument.
576
577 :param file: the file stream to use for output
578 """
579 previous = self._thread_locals.current_output_file
580 self._thread_locals.current_output_file = file
581 try:
582 yield
583 finally:
584 self._thread_locals.current_output_file = previous
585
586 def __init__(
587 self,
588 prog: str | None = None,
589 usage: str | None = None,
590 description: HelpContent | None = None,
591 epilog: HelpContent | None = None,
592 parents: Sequence[argparse.ArgumentParser] = (),
593 formatter_class: type[Cmd2HelpFormatter] = Cmd2HelpFormatter,
594 prefix_chars: str = "-",
595 fromfile_prefix_chars: str | None = None,
596 argument_default: str | None = None,
597 conflict_handler: str = "error",
598 add_help: bool = True,
599 allow_abbrev: bool = True,
600 exit_on_error: bool = True,
601 suggest_on_error: bool = False,
602 color: bool = False,
603 *,
604 ap_completer_type: type["ArgparseCompleter"] | None = None,
605 ) -> None:
606 """Initialize the Cmd2ArgumentParser instance.
607
608 :param ap_completer_type: optional parameter which specifies a subclass of ArgparseCompleter for custom completion
609 behavior on this parser. If this is None or not present, then cmd2 will use
610 argparse_completer.DEFAULT_AP_COMPLETER when completing this parser's arguments
611 """
612 kwargs: dict[str, bool] = {}
613 if sys.version_info >= (3, 14):
614 # Python >= 3.14 so pass new arguments to parent argparse.ArgumentParser class
615 kwargs = {
616 "suggest_on_error": suggest_on_error,
617 "color": color,
618 }
619
620 super().__init__(
621 prog=prog,

Calls 1

_ParserThreadLocalsClass · 0.85

Used in the wild real call sites across dependent graphs

searching dependent graphs…