#1、动态导入模块 script_name = scripts.utils module = importlib.import_module(script_name) # 动态导入相应模块 #2、模块引入检查 import importlib.util import importlib def check_module(module_name): ''' 检查module_name模块是否存在 ''' module_spec = importlib.util.find_spec(module_name) if module_spec is None: print("Module :{} not found".format(module_name)) return None else: print("Module:{} can be imported!".format(module_name)) return module_spec def import_module_from_spec(module_spec): ''' 动态导入模块 ''' module = importlib.util.module_from_spec(module_spec) module_spec.loader.exec_module(module) # module = importlib.import_module(script_name) return module if __name__ == "__main__": module_spec = check_module("fake_module") module_spec = check_module("collections") if (module_spec): module = import_module_from_spec(module_spec) print(dir(module))
参考:https://blog.csdn.net/xc_zhou/article/details/80921546
来源:https://www.cnblogs.com/snailgirl/p/10972318.html