python載入2

朵朵奇fa發表於2024-03-10
# 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")

相關文章