From eee6bf15805fa8ed3ca713a4c6e8edfd9ebc5d4e Mon Sep 17 00:00:00 2001 From: Kevin Van Brunt Date: Tue, 19 Nov 2019 22:24:13 -0500 Subject: Added capability to override the argument parser class used by cmd2 built-in commands --- examples/custom_parser.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 examples/custom_parser.py (limited to 'examples/custom_parser.py') diff --git a/examples/custom_parser.py b/examples/custom_parser.py new file mode 100644 index 00000000..efeb362e --- /dev/null +++ b/examples/custom_parser.py @@ -0,0 +1,35 @@ +# coding=utf-8 +""" +Defines the CustomParser used with override_parser.py example +""" +import sys + +from cmd2 import Cmd2ArgumentParser, set_default_argument_parser +from cmd2.ansi import style_warning + + +# First define the parser +class CustomParser(Cmd2ArgumentParser): + """Overrides error class""" + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + + def error(self, message: str) -> None: + """Custom override that applies custom formatting to the error message""" + lines = message.split('\n') + linum = 0 + formatted_message = '' + for line in lines: + if linum == 0: + formatted_message = 'Error: ' + line + else: + formatted_message += '\n ' + line + linum += 1 + + self.print_usage(sys.stderr) + formatted_message = style_warning(formatted_message) + self.exit(2, '{}\n\n'.format(formatted_message)) + + +# Now set the default parser for a cmd2 app +set_default_argument_parser(CustomParser) -- cgit v1.2.1