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')
module.hello()
example = module.Example()
example.print_info()
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)
module.hello()
example = module.Example()
example.print_info()
if __name__ == '__main__':
example1()
example2()
3. 参考
|