Debian Codegraph @

examples/custom_parser.py

raw symbols SCIP
1 """The standard parser used by cmd2 built-in commands is Cmd2ArgumentParser.
2 The following code shows how to override it with your own parser class.
3 """
4
5 import sys
6 from typing import NoReturn
7
8 from cmd2 import (
9 Cmd2ArgumentParser,
10 Cmd2Style,
11 cmd2,
12 set_default_argument_parser,
13 stylize,
14 )
15
16
17 # Since built-in commands rely on customizations made in Cmd2ArgumentParser,
18 # your custom parser class should inherit from Cmd2ArgumentParser.
19 class CustomParser(Cmd2ArgumentParser):
20 """Overrides error method."""
21
22 def __init__(self, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
23 super().__init__(*args, **kwargs)
24
25 def error(self, message: str) -> NoReturn:
26 """Custom override that applies custom formatting to the error message."""
27 lines = message.split("\n")
28 formatted_message = ""
29 for linum, line in enumerate(lines):
30 if linum == 0:
31 formatted_message = "Error: " + line
32 else:
33 formatted_message += "\n " + line
34
35 self.print_usage(sys.stderr)
36
37 # Format errors with warning style
38 formatted_message = stylize(
39 formatted_message,
40 style=Cmd2Style.WARNING,
41 )
42 self.exit(2, f"{formatted_message}\n\n")
43
44
45 if __name__ == "__main__":
46 import sys
47
48 # Set the default parser type before instantiating app.
49 set_default_argument_parser(CustomParser)
50
51 app = cmd2.Cmd(include_ipy=True, persistent_history_file="cmd2_history.dat")
52 app.self_in_py = True # Enable access to "self" within the py command
53 app.debug = True # Show traceback if/when an exception occurs
54 sys.exit(app.cmdloop())