json rpc commander 封装
This commit is contained in:
54
python_core/utils/commander/simple.py
Normal file
54
python_core/utils/commander/simple.py
Normal file
@@ -0,0 +1,54 @@
|
||||
#!/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)
|
||||
Reference in New Issue
Block a user