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

已存在__init__.py仍遇ModuleNotFoundError:找不到infra模块

解决ModuleNotFoundError: No module named 'infra'的方案

方法1:临时将src目录加入Python搜索路径

在test_auth.py开头添加代码,把src目录的绝对路径注入Python的模块搜索路径,无需修改环境变量:

import sys
from pathlib import Path

# 自动获取src目录的绝对路径(适配不同运行位置)
src_dir = Path(__file__).parent.parent
sys.path.append(str(src_dir))

from infra.agent import agent_api

方法2:设置PYTHONPATH环境变量

运行测试前,先把src目录添加到PYTHONPATH:

  • Linux/macOS终端:
export PYTHONPATH=/你的项目绝对路径/project/src:$PYTHONPATH
python src/tests/test_auth.py
  • Windows命令提示符:
set PYTHONPATH=C:\你的项目绝对路径\project\src;%PYTHONPATH%
python src/tests/test_auth.py
  • Windows PowerShell:
$env:PYTHONPATH = "C:\你的项目绝对路径\project\src;" + $env:PYTHONPATH
python src/tests/test_auth.py

方法3:以可编辑模式安装项目

进入项目根目录,执行以下命令,将项目安装为可编辑包,Python会自动识别顶层模块:

pip install -e .

之后无论从哪个目录运行测试,都能正常导入infra模块。

方法4:使用相对导入(需配合模块方式运行)

修改test_auth.py中的导入语句为相对路径:

from ...infra.agent import agent_api

然后从项目根目录以模块方式运行测试:

python -m src.tests.test_auth

内容的提问来源于stack exchange,提问作者user20395797

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:39:52