#配置文件中数据 PLUGINS = { 'disk': 'src.plugins.disk.DiskPlugin', 'mem': 'src.plugins.mem.MemPlugin', 'nic': 'src.plugins.nic.NicPlugin', } response = {} for k,v in PLUGINS.items(): #将类名从字符串分离出来 file_path,clsname=v.rsplit(".",1) file_obj=__import__(file_path,fromlist=clsname) #方式一 #import importlib #file_obj=importlib.import_module(file_path) ##方式二 if hasattr(file_obj,clsname): ret=getattr(file_obj,clsname)() response[k]=ret.execute("查看平台命令") else: raise Exception("配置文件错误") print(response) ''' 期望返回的字典内容: response = { 'disk': "disksadfasdfasdfa", 'mem': "memasdfasdfasdf", 'nic': "nicasdfasdfasdfasf", } ''' 三个py文件:src/plugins/disk.py ```python class DiskPlugin: def execute(self): return 'disksadfasdfasdfa' ``` src/plugins/mem.py ```python class MemPlugin: def execute(self): return 'memasdfasdfasdf' ``` src/plugins/nic.py ```python class NicPlugin: def execute(self): return 'nicasdfasdfasdfasf' ```
src/plugins/nic.py
class NicPlugin:
def execute(self):
return 'nicasdfasdfasdfasf'