| 1 |
|
| 2 |
"""An example cmd2 mixin.""" |
| 3 |
|
| 4 |
import functools |
| 5 |
from collections.abc import Callable |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
|
| 8 |
import cmd2 |
| 9 |
|
| 10 |
if TYPE_CHECKING: |
| 11 |
_Base = cmd2.Cmd |
| 12 |
else: |
| 13 |
_Base = object |
| 14 |
|
| 15 |
|
| 16 |
def empty_decorator(func: Callable) -> Callable: |
| 17 |
"""An empty decorator for use with your mixin.""" |
| 18 |
|
| 19 |
@functools.wraps(func) |
| 20 |
def _empty_decorator(self, *args, **kwargs) -> None: |
| 21 |
self.poutput("in the empty decorator") |
| 22 |
func(self, *args, **kwargs) |
| 23 |
|
| 24 |
_empty_decorator.__doc__ = func.__doc__ |
| 25 |
return _empty_decorator |
| 26 |
|
| 27 |
|
| 28 |
class MyMixin(_Base): |
| 29 |
"""A mixin class which adds a 'say' command to a cmd2 subclass. |
| 30 |
|
| 31 |
The order in which you add the mixin matters. Say you want to |
| 32 |
use this mixin in a class called MyApp. |
| 33 |
|
| 34 |
class MyApp(MyMixin, cmd2.Cmd): |
| 35 |
def __init__(self, *args, **kwargs): |
| 36 |
# gotta have this or neither the mixin or cmd2 will initialize |
| 37 |
super().__init__(*args, **kwargs) |
| 38 |
""" |
| 39 |
|
| 40 |
def __init__(self, *args, **kwargs) -> None: |
| 41 |
|
| 42 |
super().__init__(*args, **kwargs) |
| 43 |
|
| 44 |
|
| 45 |
self.register_preloop_hook(self.cmd2_mymixin_preloop_hook) |
| 46 |
self.register_postloop_hook(self.cmd2_mymixin_postloop_hook) |
| 47 |
self.register_postparsing_hook(self.cmd2_mymixin_postparsing_hook) |
| 48 |
|
| 49 |
def do_say(self, statement) -> None: |
| 50 |
"""Simple say command.""" |
| 51 |
self.poutput(statement) |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
def cmd2_mymixin_preloop_hook(self) -> None: |
| 56 |
"""Method to be called before the command loop begins.""" |
| 57 |
self.poutput("preloop hook") |
| 58 |
|
| 59 |
def cmd2_mymixin_postloop_hook(self) -> None: |
| 60 |
"""Method to be called after the command loop finishes.""" |
| 61 |
self.poutput("postloop hook") |
| 62 |
|
| 63 |
def cmd2_mymixin_postparsing_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: |
| 64 |
"""Method to be called after parsing user input, but before running the command.""" |
| 65 |
self.poutput("in postparsing hook") |
| 66 |
return data |
| 67 |
|
| 68 |
|
| 69 |
class Example(MyMixin, cmd2.Cmd): |
| 70 |
"""An class to show how to use a mixin.""" |
| 71 |
|
| 72 |
def __init__(self, *args, **kwargs) -> None: |
| 73 |
|
| 74 |
super().__init__(*args, **kwargs) |
| 75 |
|
| 76 |
@empty_decorator |
| 77 |
def do_something(self, _arg) -> None: |
| 78 |
self.poutput("this is the something command") |
| 79 |
|
| 80 |
|
| 81 |
if __name__ == "__main__": |
| 82 |
app = Example() |
| 83 |
app.cmdloop() |