Python3.9本地包导入报错:ModuleNotFoundError: No module named 'ptmodeling'
模块导入问题分析与解决
项目结构
├── README.md ├── src/ │ └── ptmodeling │ ├── __init__.py │ ├── driver.py │ ├── features.py │ └── modeling.py └── tests/
问题描述
在src/ptmodeling目录下执行python3 driver.py时,出现ModuleNotFoundError: No module named 'ptmodeling'错误。尝试从项目根目录运行、配置PYTHONPATH后,使用以下driver.py仍无法解决问题:
无法运行的driver.py代码
import logging import os import sys sys.path.append(os.getcwd()) print(sys.path) from ptmodeling.modeling import ModelEngine from ptmodeling.features import FeatureExtractor
可正常运行的driver.py代码
import logging import os import sys sys.path.append(os.getcwd()) print(sys.path) from modeling import Model from features import Feature
问题原因
核心是Python的模块查找路径逻辑:
- 当在
ptmodeling目录内直接运行脚本时,os.getcwd()返回的是src/ptmodeling,把这个路径加到sys.path后,Python只会在这个目录下找模块。但ptmodeling作为一个包,它的父目录src不在sys.path里,所以用ptmodeling.modeling这种绝对导入方式找不到模块。 - 第二种写法直接导入同目录下的文件,Python会优先在当前脚本所在目录查找,所以能运行,但这种写法不规范,后续如果项目结构调整很容易出问题。
解决办法
方法1:修改脚本,把src目录加入sys.path
修改driver.py,让Python能找到ptmodeling包的父目录:
import logging import os import sys # 获取当前脚本所在目录的父目录(也就是src目录) src_path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(src_path) from ptmodeling.modeling import ModelEngine from ptmodeling.features import FeatureExtractor
如果要更稳妥地定位项目根目录,可以这么写:
import logging import os import sys # 从当前脚本目录往上两级,定位到项目根目录 root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")) sys.path.append(root_path) from ptmodeling.modeling import ModelEngine from ptmodeling.features import FeatureExtractor
方法2:从项目根目录运行脚本
直接在项目根目录执行命令,不用改脚本:
python3 src/ptmodeling/driver.py
此时Python会自动把项目根目录加入模块查找路径,ptmodeling作为src下的包就能被正常识别。
方法3:设置PYTHONPATH环境变量
先把src目录加到PYTHONPATH,再运行脚本:
# Linux/macOS 终端 export PYTHONPATH=/你的项目路径/src:$PYTHONPATH cd src/ptmodeling python3 driver.py # Windows PowerShell $env:PYTHONPATH = "C:\你的项目路径\src;" + $env:PYTHONPATH cd src/ptmodeling python3 driver.py
内容的提问来源于stack exchange,提问作者Brain Monkey
相关产品推荐
相关产品推荐

