diff options
Diffstat (limited to 'examples')
-rwxr-xr-x | examples/exit_code.py | 43 | ||||
-rwxr-xr-x | examples/tab_autocompletion.py | 11 |
2 files changed, 47 insertions, 7 deletions
diff --git a/examples/exit_code.py b/examples/exit_code.py new file mode 100755 index 00000000..8ae2d310 --- /dev/null +++ b/examples/exit_code.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python +# coding=utf-8 +"""A simple example demonstrating the following how to emit a non-zero exit code in your cmd2 application. +""" +import cmd2 +import sys +from typing import List + + +class ReplWithExitCode(cmd2.Cmd): + """ Example cmd2 application where we can specify an exit code when existing.""" + + def __init__(self): + super().__init__() + + @cmd2.with_argument_list + def do_exit(self, arg_list: List[str]) -> bool: + """Exit the application with an optional exit code. + +Usage: exit [exit_code] + Where: + * exit_code - integer exit code to return to the shell +""" + # If an argument was provided + if arg_list: + try: + self.exit_code = int(arg_list[0]) + except ValueError: + self.perror("{} isn't a valid integer exit code".format(arg_list[0])) + self.exit_code = -1 + + self._should_quit = True + return self._STOP_AND_EXIT + + def postloop(self) -> None: + """Hook method executed once when the cmdloop() method is about to return.""" + code = self.exit_code if self.exit_code is not None else 0 + self.poutput('{!r} exiting with code: {}'.format(sys.argv[0], code)) + + +if __name__ == '__main__': + app = ReplWithExitCode() + app.cmdloop() diff --git a/examples/tab_autocompletion.py b/examples/tab_autocompletion.py index 38972358..6a2e683e 100755 --- a/examples/tab_autocompletion.py +++ b/examples/tab_autocompletion.py @@ -125,7 +125,9 @@ class TabCompleteExample(cmd2.Cmd): # - The help output for arguments with multiple flags or with append=True is more concise # - ACArgumentParser adds the ability to specify ranges of argument counts in 'nargs' - suggest_parser = argparse_completer.ACArgumentParser() + suggest_description = "Suggest command demonstrates argparse customizations.\n" + suggest_description += "See hybrid_suggest and orig_suggest to compare the help output." + suggest_parser = argparse_completer.ACArgumentParser(description=suggest_description) suggest_parser.add_argument('-t', '--type', choices=['movie', 'show'], required=True) suggest_parser.add_argument('-d', '--duration', nargs=(1, 2), action='append', @@ -136,12 +138,7 @@ class TabCompleteExample(cmd2.Cmd): @cmd2.with_category(CAT_AUTOCOMPLETE) @cmd2.with_argparser(suggest_parser) def do_suggest(self, args) -> None: - """Suggest command demonstrates argparse customizations - - See hybrid_suggest and orig_suggest to compare the help output. - - - """ + """Suggest command demonstrates argparse customizations""" if not args.type: self.do_help('suggest') |