Python模块导入问题:如何调用引用子文件夹模块的模块?
Python模块导入问题解决方案
文件夹结构
root module_a hello.py submodule_a hi.py module_b howdy.py
各文件代码
hi.py
def myhi(hi): print("myhi " + hi)
hello.py
from submodule_a.hi import myhi def myhello(hello): myhi("myhello " + hello)
howdy.py
from module_a.hello import myhello def myhowdy(howdy): myhello("myhowdy " + howdy)
问题描述
运行howdy.py时最初无法找到module_a,添加sys.path.append(".")后,howdy.py能定位module_a,但hello.py又无法找到submodule_a。要求**完全不修改hello.py**解决该问题。
解决方案
方案1:修改howdy.py的路径配置 + 添加包标识文件
- 在
module_a和submodule_a目录下各创建空的__init__.py文件,让Python将它们识别为可导入的包:root module_a __init__.py hello.py submodule_a __init__.py hi.py module_b howdy.py - 修改
howdy.py,将root目录和module_a目录加入Python的模块搜索路径:
此配置既保证import sys from pathlib import Path # 获取root目录的绝对路径 root_dir = Path(__file__).parent.parent # 获取module_a目录的绝对路径 module_a_dir = root_dir / "module_a" # 加入搜索路径 sys.path.append(str(root_dir)) sys.path.append(str(module_a_dir)) from module_a.hello import myhello def myhowdy(howdy): myhello("myhowdy " + howdy)howdy.py能找到module_a.hello,又让hello.py里的from submodule_a.hi import myhi能正确定位到submodule_a。
方案2:通过环境变量配置(无需修改代码)
- 同样在
module_a和submodule_a下创建空__init__.py文件。 - 进入
root目录,执行对应操作系统的命令:- Linux/macOS终端:
export PYTHONPATH=$PYTHONPATH:./module_a python module_b/howdy.py - Windows PowerShell:
$env:PYTHONPATH += ";.\module_a" python module_b/howdy.py
module_a加入Python搜索路径,无需修改任何代码文件。 - Linux/macOS终端:
内容的提问来源于stack exchange,提问作者joluong
相关产品推荐
相关产品推荐

