You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

报错情况

  1. 执行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'
  1. 修改为相对导入后(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 08:47:23