Python | 动态加载模块

1. 文件结构

hello-python
├── commands
│   └── command1.py
└── main.py

2. 代码

command1.py

def hello():
    print("this is command1")


class Example:
    def print_info(self):
        print(f'this is {self.__class__}')


print('command1.py loaded')

main.py

import importlib
import os.path


def example1():
    # 导入执行模块
    module = importlib.import_module('commands.command1')  # Output: command1.py loaded
    module.hello()  # Output: this is command1l
    example = module.Example()
    example.print_info()  # Output: this is <class 'command1.Example'>


def example2():
    file_path = 'commands/command1.py'
    module_name = 'command1'

    # 加载模块
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)

    # 执行模块
    spec.loader.exec_module(module)  # Output: command1.py loaded

    # 调用模块方法
    module.hello()  # Output: this is command1l

    # 调用模块类
    example = module.Example()
    example.print_info()  # Output: this is <class 'command1.Example'>


if __name__ == '__main__':
    example1()
    example2()

3. 参考

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐