Spaces:
Sleeping
Sleeping
| 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 | |