Python测试项目配置异常:无法导入model模块中的类
Python测试项目模块导入失败问题解决
项目结构
. ├── model │ ├── __init__.py │ └── user.py └── test ├── __init__.py └── test_user.py
文件内容
model/user.py:
class User: pass
test/test_user.py(绝对导入版本):
from model.user import User
报错情况
- 执行
python test/test_user.py时:
Traceback (most recent call last): File "/tmp/minimal_example/test/test_user.py", line 1, in <module> from model.user import User ModuleNotFoundError: No module named 'model'
- 修改为相对导入后(
test/test_user.py):
from ..model.user import User
执行python test/test_user.py时报错:
Traceback (most recent call last): File "/tmp/minimal_example/test/test_user.py", line 1, in <module> from ..model.user import User ImportError: attempted relative import with no known parent package
解决方法
方法1:从项目根目录以包形式运行测试
切换到包含model和test的项目根目录,执行以下命令:
python -m test.test_user
这种方式会将根目录加入Python模块搜索路径,同时让Python识别test为合法包,相对导入也能正常生效。
方法2:设置PYTHONPATH环境变量
运行脚本前,将项目根目录添加到PYTHONPATH:
- Linux/macOS:
export PYTHONPATH=/path/to/your/project/root python test/test_user.py
- Windows(命令提示符):
set PYTHONPATH=C:\path\to\your\project\root python test/test_user.py
配置后Python就能找到model模块,绝对导入可正常使用。
方法3:调整导入路径(不推荐)
在test_user.py开头添加代码,手动将项目根目录加入sys.path:
import sys from pathlib import Path # 获取项目根目录路径 project_root = Path(__file__).parent.parent sys.path.append(str(project_root)) from model.user import User
该方法虽能解决问题,但会耦合文件路径,项目结构变动时极易出错。
内容的提问来源于stack exchange,提问作者Dakkar
相关产品推荐
相关产品推荐

