File: custom_parser.py

package info (click to toggle)
cmd2 2.5.11%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 10,244 kB
  • sloc: python: 19,643; makefile: 73; sh: 67; javascript: 30
file content (42 lines) | stat: -rw-r--r-- 1,098 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# coding=utf-8
"""
Defines the CustomParser used with override_parser.py example
"""

import sys

from cmd2 import (
    Cmd2ArgumentParser,
    ansi,
    set_default_argument_parser_type,
)


# 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)

        # Format errors with style_warning()
        formatted_message = ansi.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_type(CustomParser)