Spaces:
Sleeping
Sleeping
File size: 1,758 Bytes
07cb7d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | import sys
from typing import Callable
def action(method: Callable) -> Callable:
method.__action__ = True
return method
class ActionRunner:
def __call__(self, default_method: str | Callable = None):
if len(sys.argv) > 1:
method = self._resolve_method(sys.argv[1])
action_args = self._resolve_action_args(sys.argv[2:])
elif default_method is None:
method = self.print_actions
action_args = {}
elif callable(default_method):
method = default_method
action_args = {}
else:
method = self._resolve_method(default_method)
action_args = {}
if method:
method(**action_args)
else:
raise ValueError("没有指定要执行的方法")
def print_actions(self):
print(f"可用动作: {', '.join(self._action_names())}")
def _action_names(self) -> list[str]:
names = []
for runner_class in reversed(self.__class__.mro()):
for name, method in runner_class.__dict__.items():
if getattr(method, "__action__", False):
names.append(name)
return names
def _resolve_method(self, method_name: str) -> Callable:
method = getattr(self, method_name, None)
if method is None:
raise ValueError(f"没有找到对应的方法:{method_name}")
return method
def _resolve_action_args(self, args: list[str]) -> dict:
action_args = {}
for arg in args:
if "=" in arg:
name, value = arg.split("=", 1)
action_args[name] = value
else:
action_args[arg] = True
return action_args
|