欢迎访问宙启技术站
智能推送

使用python中的importlibutil()模块实现模块的动态修改

发布时间:2023-12-28 01:25:16

import importlib.util

# 动态加载模块

def load_module(module_name):

    spec = importlib.util.find_spec(module_name)

    module = importlib.util.module_from_spec(spec)

    spec.loader.exec_module(module)

    return module

# 动态修改模块的函数

def modify_module(module, function_name, new_function):

    if hasattr(module, function_name) and callable(getattr(module, function_name)):

        setattr(module, function_name, new_function)

        return True

    else:

        return False

# 示例模块

def hello():

    print("Hello, World!")

# 加载示例模块

module = load_module("example_module")

# 调用示例模块的函数

module.hello()  # 输出:Hello, World!

# 定义新的函数

def new_hello():

    print("New Hello, World!")

# 修改示例模块的函数

success = modify_module(module, "hello", new_hello)

if success:

    # 调用修改后的函数

    module.hello()  # 输出:New Hello, World!

else:

    print("Failed to modify module")