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()
本文介绍了如何在Python中动态地加载和执行模块。通过`importlib`库的`import_module`函数和`spec_from_file_location`配合`module_from_spec`,可以实现从指定路径加载模块并调用其方法。示例代码展示了两种不同的加载和执行模块的方法。
599

被折叠的 条评论
为什么被折叠?



