summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/custom_parser.py35
-rwxr-xr-xexamples/override_parser.py24
2 files changed, 59 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)
diff --git a/examples/override_parser.py b/examples/override_parser.py
new file mode 100755
index 00000000..ddfa8323
--- /dev/null
+++ b/examples/override_parser.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python
+# coding=utf-8
+# flake8: noqa F402
+"""
+The standard parser used by cmd2 built-in commands is Cmd2ArgumentParser.
+The following code shows how to override it with your own parser class.
+"""
+
+# First set a value called argparse.cmd2_parser_module with the module that defines the custom parser
+# See the code for custom_parser.py. It simply defines a parser and calls cmd2.set_default_argument_parser()
+# with the custom parser's type.
+import argparse
+argparse.cmd2_parser_module = 'examples.custom_parser'
+
+# Next import stuff from cmd2. It will import your module just before the cmd2.Cmd class file is imported
+# and therefore override the parser class it uses on its commands.
+from cmd2 import cmd2
+
+if __name__ == '__main__':
+ import sys
+ app = cmd2.Cmd(use_ipython=True, persistent_history_file='cmd2_history.dat')
+ app.locals_in_py = True # Enable access to "self" within the py command
+ app.debug = True # Show traceback if/when an exception occurs
+ sys.exit(app.cmdloop())