Python跨同级目录导入函数:解决'code不是包'的ModuleNotFoundError报错
错误原因
你在agents.py中使用from code.helpers import some_function时,Python会从执行脚本的工作目录(也就是你运行main.py时的code目录)搜索顶层包code,自然无法找到——因为code本身就是当前的顶层目录,不需要额外加code前缀。
可行解决方案
方案1:使用包内相对导入(最适配当前场景)
- 在
agents/agents.py中写入导入语句:
from ..helpers.helpers import some_function
语法说明:两个点代表向上跳转一级目录(从agents目录跳到code根目录),再定位到helpers目录下的helpers模块。
- 在
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
相关产品推荐
相关产品推荐

