Python中importlib.import_module导入模块

本文介绍了Python中使用importlib.import_module动态导入模块的方法,包括如何进行相对导入和绝对导入,并通过具体代码示例详细解释了导入过程。在文件结构的背景下,展示了在不同层级目录下导入模块的实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、文件结构:

├── clazz
│   ├── __init__.py
│   ├── a.py
│   └── b.py
└── main.py

a.py 的代码

def show():
    print("show A")

b.py 的代码

def show():
    print("show B")

从main中导入clazz包中的a 和b 模块
main.py

import importlib

# 绝对导入
a = importlib.import_module("clazz.a")
a.show()
# 打印结果:show A

# 相对导入
b = importlib.import_module(".b", "clazz")
b.show()
# 打印结果:show B

注意,相对导入有个一点., 类似路径。

2.在一定文件下设定:
文件结构:

│──web_ui_auto_lib
│	├── element_behavior_handlers
│	│   ├── __init__.py
│	│   ├── check_behavior_handler.py
│	│   └── click_behavior_handler.py
│	│   └── close_behavior_handler.py
│	│   └── f5_behavior_handler.py
│	└── main.py

main.py文件下:

# step.Behavior 是遍历步骤的名称:[check,click,close,f5]
module_name = "web_ui_auto_lib." + "element_behavior_handlers." + step.Behavior + "_behavior_handler"  
# 每个py文件中的类名以 [check,click,close,f5] + BehaviorHandler
class_name = step.Behavior + "BehaviorHandler"
module = importlib.import_module(module_name)
# 对象可以引用 module_name 文件 + 类名,
# 所有check_behavior_handler.py,click_behavior_handler.py,close_behavior_handler.py,f5_behavior_handler.py文件下都是 handle_behavior 这个方法
aclass = getattr(module, class_name)
time.sleep(int(step.WaitTime))
handle_behavior = getattr(aclass, "handle_behavior")
returnvalue = handle_behavior(aclass(), self.bm, step)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值