From 2b2110ad24b64d022128051169a3515257922c8f Mon Sep 17 00:00:00 2001 From: Todd Leonhardt Date: Thu, 23 Aug 2018 23:36:42 -0400 Subject: Added way of returning a non-zero exit code to the shell --- examples/exit_code.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100755 examples/exit_code.py (limited to 'examples/exit_code.py') diff --git a/examples/exit_code.py b/examples/exit_code.py new file mode 100755 index 00000000..e5a896da --- /dev/null +++ b/examples/exit_code.py @@ -0,0 +1,45 @@ +#!/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 + print('{!r} exiting with code: {}'.format(sys.argv[0], code)) + + +if __name__ == '__main__': + app = ReplWithExitCode() + app.cmdloop() -- cgit v1.2.1 From d567570faf490d052f3f74a65a6af6aa338d965a Mon Sep 17 00:00:00 2001 From: Todd Leonhardt Date: Thu, 23 Aug 2018 23:59:42 -0400 Subject: Added a couple unit tests of the exit code feature --- examples/exit_code.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'examples/exit_code.py') diff --git a/examples/exit_code.py b/examples/exit_code.py index e5a896da..8ae2d310 100755 --- a/examples/exit_code.py +++ b/examples/exit_code.py @@ -33,11 +33,9 @@ Usage: exit [exit_code] return self._STOP_AND_EXIT def postloop(self) -> None: - """Hook method executed once when the cmdloop() method is about to return. - - """ + """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 - print('{!r} exiting with code: {}'.format(sys.argv[0], code)) + self.poutput('{!r} exiting with code: {}'.format(sys.argv[0], code)) if __name__ == '__main__': -- cgit v1.2.1