我的环境是:os系统 python 3.7

在学这个模块之前我们先获取下该模块的路径如下:

>>>import module

>>>print(module.__file__)

 实例:

1. 获取importlib模块的绝对路径结果文件

Python Importlib.import_module动态导入模块

2. 获取importlib模块的路径名

Python Importlib.import_module动态导入模块

 

 下面开始正题:

文件结构如下:

Python Importlib.import_module动态导入模块

  • a.py 的代码
def show():
print("show A")
  • b.py 的代码
def show():
print("show B")
  • 从main中导入test包中的a和b模块,main.py的代码如下
 1 import importlib
 2 
 3 # 绝对导入
 4 a = importlib.import_module("test.a")
 5 a.show()
 6 # 输出show A
 7 
 8 # 相对导入
 9 b = importlib.import_module(".b", "test")
10 b.show()
11 # 输出show B

注意:“.” 类似路径

 

相关文章:

  • 2021-06-19
  • 2021-07-30
  • 2022-12-23
  • 2022-01-20
猜你喜欢
  • 2022-03-09
  • 2022-02-27
  • 2021-12-06
  • 2022-12-23
  • 2022-12-23
  • 2021-12-20
  • 2021-06-13
相关资源
相似解决方案