# testInstance.py # 导入需要的模块 import importlib # 导入模块以动态加载库中的类和函数 import sys # 导入系统模块,用于操作Python解释器的参数和变量 import os import pkgutil # 定义TestInstance类 class TestInstance: # 初始化方法,当创建TestInstance对象时调用 def __init__(self, projectName): # 初始化实例变量projectName,存储项目名称 self.projectName = projectName self.libraries = {} # 调用load_libraries方法加载库,并将结果存储在self.lib中 # self.lib = self.load_libraries() # 定义load_libraries方法,用于加载库 def __getattr__(self, item): print("item",item) libs = self.load_libraries(item) return libs def list_submodules(self, package_path): """递归地列出给定包路径下的所有子模块""" all_submodules = [] # 遍历包路径下的所有文件/目录 for importer, modname, ispkg in pkgutil.iter_modules([package_path]): full_modname = modname module_path = os.path.join(package_path, modname) # 如果是子包,则递归调用list_submodules if ispkg: # 构建子包的完整路径 subpackage_path = os.path.join(module_path, '__init__.py') # 递归查找子包下的子模块 submodules = self.list_submodules(subpackage_path) # 添加子模块名称到结果列表,同时保留子包的路径 all_submodules.extend([full_modname + '.' + submodule for submodule in submodules]) else: # 添加非包模块的完整名称 all_submodules.append(full_modname) return all_submodules def import_module_by_path(self, module_path, module_name): """ 根据给定的完整路径动态导入模块 """ spec = importlib.util.spec_from_file_location(module_name, module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def load_libraries(self,lib): # 导入配置模块 import libconfig # 假设存在一个名为libconfig的模块,其中包含库的加载顺序等信息 # 初始化一个空字典,用于存储库中的类和函数 libraries = {} print("sys.path", sys.path) # 按照配置模块中指定的顺序加载库 root = r"C:\Users\15773\Desktop\文心一言\新建文件夹\test_library" for lib_name in libconfig.libraries_order: # 遍历库名列表 # sys.path.insert(0,os.path.join(root, lib_name)) libPath = os.path.abspath(os.path.join(root, lib_name)) print("libPath", libPath, lib_name) allPac = self.list_submodules(libPath) print("allPac", allPac) # libName = allPac[item] if lib in allPac: libPath = os.path.join(libPath, lib + ".py") module = self.import_module_by_path(libPath, lib) myclass = getattr(module, lib) libraries.update( {attr_name: getattr(myclass, attr_name) for attr_name in dir(myclass) if not attr_name.startswith('_')}) print("libraries", libraries) return libraries if __name__ == '__main__': # 假设当前项目名称为"projectlib" projectName = "projectA" # 创建TestInstance对象 test = TestInstance(projectName) print("test.lib", test.libA) test.libA.greet("hello")
标签:name,lib,python,self,module,libraries,path,加载 From: https://www.cnblogs.com/shunguo/p/18064850