Python能否将导入文件名设为变量以实现跨目录导入文件?
Python动态导入变量指定模块的实现方法
问题结论
可以将导入的模块名设置为变量实现动态导入,Python标准库提供了importlib.import_module接口专门处理这类需求,不需要硬编码import语句。
实现步骤
1. 确认模块的导入路径
Python导入模块使用点分路径格式,不需要加.py后缀,和你项目的包结构对应即可,以你给出的目录结构为例,各模块的导入路径如下:
- file1.py:
myapp.dir1.file1(全局绝对路径),如果在bar/calling_function.py内用相对路径则是..dir1.file1 - file2.py:
myapp.dir2.file2(全局绝对路径) - foo.py:
myapp.foo(全局绝对路径)
如果运行时提示找不到模块,可以手动将myapp的上层目录加入Python的模块搜索路径:
import sys sys.path.append("/path/to/parent/directory/of/myapp")
2. 修正代码逻辑
你原来的硬编码from module_dict[value] import common_function写法不支持变量传参,替换为动态导入逻辑即可,完整可运行代码如下:
from importlib import import_module # 字典value存模块的点分导入路径 module_dict = { "key1": "myapp.dir1.file1", "key2": "myapp.dir2.file2", "key3": "myapp.foo" } def call_common_func(arguments, module_dict): # 遍历所有模块路径 for module_path in module_dict.values(): # 动态导入模块 mod = import_module(module_path) # 从模块中获取common_function方法,不存在则返回None common_function = getattr(mod, "common_function", None) if callable(common_function): # 方法存在则调用 common_function(arguments) else: print(f"警告:模块{module_path}中不存在可用的common_function")
3. 相对导入适配(可选)
如果需要在包内部使用相对路径导入,不需要写全myapp前缀,可以给import_module加package参数指定当前包上下文:
# 位于bar/calling_function.py中时使用相对路径导入 mod = import_module("..dir1.file1", package=__name__)
内容的提问来源于stack exchange,提问作者user215865
相关产品推荐
相关产品推荐

