summaryrefslogtreecommitdiff
path: root/examples/custom_parser.py
diff options
context:
space:
mode:
authorTodd Leonhardt <todd.leonhardt@gmail.com>2019-11-22 21:57:25 -0500
committerGitHub <noreply@github.com>2019-11-22 21:57:25 -0500
commit1cad8d92b87a227b331c0e86ddbbee25a6742650 (patch)
tree473f2e533aa34f2b4811a01bf18746aaf8471c0c /examples/custom_parser.py
parent8c00d342ee3967e09cce436d76208238307d1cd4 (diff)
parent0d6e9cbd254b8f9911a0d6aad1edb913e95fff45 (diff)
downloadcmd2-git-1cad8d92b87a227b331c0e86ddbbee25a6742650.tar.gz
Merge pull request #812 from python-cmd2/custom_parser
Custom parser
Diffstat (limited to 'examples/custom_parser.py')
-rw-r--r--examples/custom_parser.py35
1 files changed, 35 insertions, 0 deletions
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)