summaryrefslogtreecommitdiff
path: root/examples/exit_code.py
diff options
context:
space:
mode:
authorKevin Van Brunt <kmvanbrunt@gmail.com>2018-09-01 11:50:37 -0400
committerKevin Van Brunt <kmvanbrunt@gmail.com>2018-09-01 11:50:37 -0400
commit610aad33eb8fe1772480e98af8b255bd56dfe78c (patch)
treeb9dfb60fa0a60b438c8b8e31679f6df768f24665 /examples/exit_code.py
parent20f4a52399c5c1ee87ae57b9f082113663b20060 (diff)
parent93d40a4a486ae6121858f9fb7369ed272a768672 (diff)
downloadcmd2-git-610aad33eb8fe1772480e98af8b255bd56dfe78c.tar.gz
Merge branch 'quoted_args' of github.com:python-cmd2/cmd2 into quoted_args
Diffstat (limited to 'examples/exit_code.py')
-rwxr-xr-xexamples/exit_code.py43
1 files changed, 43 insertions, 0 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()