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
| class Meta(type): def __init__(cls, name, bases, attrs): cls.module = name.lower() super().__init__(name, bases, attrs)
sub_module = attrs.get('sub_module', []) parent_module = attrs.get('parent_module', '') if isinstance(sub_module, list): for module in sub_module: method = cls.generate_method(parent_module, module) setattr(cls, module, classmethod(method)) elif isinstance(sub_module, dict): for k, module in sub_module.items(): method = cls.generate_method(parent_module, module) setattr(cls, k, classmethod(method)) else: raise f"sub_module type error: {type(sub_module)}, expect list or dict"
@staticmethod def generate_method(parent_module, sub_module) -> Callable[..., str]: def method(cls, *args, **kwargs): return cls.build_command(parent_module, sub_module, *args, **kwargs)
return method
def build_command(cls, parent_module, sub_module, *args, **kwargs): args_str = " ".join(map(str, args)) kwargs_str = " ".join([f"--{key}={value}" for key, value in kwargs.items() if value != ""]) return f"{parent_module} {cls.module} {sub_module} {args_str} {kwargs_str} "
def __getattr__(cls, attr): raise AttributeError(f"'{cls.__name__}' class has no attribute '{attr}'")
def help(cls): for attr_name in cls.sub_module: attr = getattr(cls, attr_name) if not callable(attr): raise TypeError(f"attribute '{attr_name}' is not callable") print(f"Available methods: {list(cls.sub_module)}") print(f"Example usage: {cls.__name__}.{list(cls.sub_module)[0]}('argument')")
|