forked from python-cmd2/cmd2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcustom_parser.py
41 lines (32 loc) · 1.07 KB
/
custom_parser.py
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
# 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)