mxivideo/python_core/utils/commander/simple.py

55 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
简化的JSON-RPC Commander
"""
from typing import Dict, Any, List, Callable
from .base import JSONRPCCommander
class SimpleJSONRPCCommander(JSONRPCCommander):
"""简化的JSON-RPC Commander用于快速创建命令行工具"""
def __init__(self, service_name: str):
self.command_handlers: Dict[str, Callable] = {}
super().__init__(service_name)
def _register_commands(self) -> None:
"""默认不注册任何命令"""
pass
def add_command(self,
name: str,
handler: Callable,
description: str,
required_args: List[str] = None,
optional_args: Dict[str, Dict[str, Any]] = None) -> None:
"""
添加命令处理器
Args:
name: 命令名称
handler: 命令处理函数
description: 命令描述
required_args: 必需参数列表
optional_args: 可选参数配置
"""
self.register_command(name, description, required_args, optional_args)
self.command_handlers[name] = handler
# 重新创建parser以包含新命令
from .parser import ArgumentParser
self.parser = ArgumentParser(self.commands)
def execute_command(self, command: str, args: Dict[str, Any]) -> Any:
"""执行命令"""
if command not in self.command_handlers:
raise ValueError(f"No handler for command: {command}")
handler = self.command_handlers[command]
return handler(**args)
# 便捷函数
def create_simple_commander(service_name: str) -> SimpleJSONRPCCommander:
"""创建简单的JSON-RPC Commander"""
return SimpleJSONRPCCommander(service_name)