| 1 |
|
| 2 |
"""A simple example demonstrating the following how to emit a non-zero exit code in your cmd2 application.""" |
| 3 |
|
| 4 |
import cmd2 |
| 5 |
|
| 6 |
|
| 7 |
class ReplWithExitCode(cmd2.Cmd): |
| 8 |
"""Example cmd2 application where we can specify an exit code when existing.""" |
| 9 |
|
| 10 |
def __init__(self) -> None: |
| 11 |
super().__init__() |
| 12 |
|
| 13 |
@cmd2.with_argument_list |
| 14 |
def do_exit(self, arg_list: list[str]) -> bool: |
| 15 |
"""Exit the application with an optional exit code. |
| 16 |
|
| 17 |
Usage: exit [exit_code] |
| 18 |
Where: |
| 19 |
* exit_code - integer exit code to return to the shell |
| 20 |
""" |
| 21 |
|
| 22 |
if arg_list: |
| 23 |
try: |
| 24 |
self.exit_code = int(arg_list[0]) |
| 25 |
except ValueError: |
| 26 |
self.perror(f"{arg_list[0]} isn't a valid integer exit code") |
| 27 |
self.exit_code = 1 |
| 28 |
|
| 29 |
return True |
| 30 |
|
| 31 |
|
| 32 |
if __name__ == "__main__": |
| 33 |
import sys |
| 34 |
|
| 35 |
app = ReplWithExitCode() |
| 36 |
sys_exit_code = app.cmdloop() |
| 37 |
app.poutput(f"{sys.argv[0]!r} exiting with code: {sys_exit_code}") |
| 38 |
sys.exit(sys_exit_code) |