Python项目导入folderb模块报错ModuleNotFoundError的问题排查
问题分析与解决
问题根源
当你直接运行foldera/filea.py时,Python会将**当前脚本所在的目录(即/root/Documents/Repositories/mainproject/foldera/)**加入模块搜索路径sys.path,而非项目根目录mainproject。因此解释器无法定位到上层目录中的folderb模块。
可行解决方法
方法1:使用相对导入
修改filea.py中的导入语句为相对路径格式,指向同级的folderb目录:
from ..folderb.fileb import myfunctionb
注意:这种方式仅在将mainproject作为包导入时生效,不能直接运行filea.py(直接运行会触发ValueError: attempted relative import beyond top-level package)。需从项目根目录的上级目录执行:
cd /root/Documents/Repositories/ python -m mainproject.foldera.filea
方法2:手动添加项目根目录到搜索路径
在filea.py的最顶部添加代码,将项目根目录注入sys.path:
import sys import os # 获取当前脚本所在目录的上层目录(即mainproject路径) project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(project_root) # 后续正常导入 from folderb.fileb import myfunctionb
修改后无论从哪个路径运行filea.py,都能正确找到folderb模块。
方法3:设置PYTHONPATH环境变量
在终端中先配置环境变量,将项目根目录加入Python搜索路径,再执行脚本:
# Linux/macOS export PYTHONPATH=/root/Documents/Repositories/mainproject:$PYTHONPATH python /root/Documents/Repositories/mainproject/foldera/filea.py # Windows(命令提示符) set PYTHONPATH=C:\root\Documents\Repositories\mainproject;%PYTHONPATH% python C:\root\Documents\Repositories\mainproject\foldera\filea.py
该方式无需修改代码,适合临时测试场景。
内容的提问来源于stack exchange,提问作者Arie
相关产品推荐
相关产品推荐

