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

Python跨同级目录导入函数:解决'code不是包'的ModuleNotFoundError报错

错误原因

你在agents.py中使用from code.helpers import some_function时,Python会从执行脚本的工作目录(也就是你运行main.py时的code目录)搜索顶层包code,自然无法找到——因为code本身就是当前的顶层目录,不需要额外加code前缀。

可行解决方案

方案1:使用包内相对导入(最适配当前场景)

  1. 在agents/agents.py中写入导入语句:
from ..helpers.helpers import some_function

语法说明:两个点代表向上跳转一级目录(从agents目录跳到code根目录),再定位到helpers目录下的helpers模块。

  1. 在main.py中写入导入语句:
# 导入helpers模块所有内容
from helpers.helpers import *
# 导入agents模块所有内容
from agents.agents import *

直接在code目录下执行python main.py即可正常运行。

如果想要简化导入语句,可以分别在两个子目录的__init__.py中配置导出内容:

  • 在helpers/__init__.py中添加:
from .helpers import *
  • 在agents/__init__.py中添加:
from .agents import *

之后就可以把导入语句简化为:

  • agents.py内:from ..helpers import some_function
  • main.py内:from helpers import *、from agents import *

方案2:保留绝对导入,调整运行方式

如果坚持要使用带code前缀的绝对导入,需要退到code目录的上级目录,用模块方式运行main.py:

python -m code.main

此时agents.py中的from code.helpers.helpers import some_function可以正常生效。

方案3:手动添加模块搜索路径

如果不想调整运行方式和导入逻辑,可以在main.py最开头添加代码,把当前code目录加入Python的模块搜索路径:

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

之后agents.py中直接写from helpers.helpers import some_function即可正常运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:54:00