You need to enable JavaScript to run this app. Python控制台应用运行报ModuleNotFoundError:无法找到自定义DataServices模块
优惠活动
大模型
产品
解决方案
定价
更多

Python控制台应用运行报ModuleNotFoundError:无法找到自定义DataServices模块

问题核心原因

Python运行脚本时默认仅将当前脚本所在的目录加入模块搜索路径,你运行Baseball_DataImport.py时搜索路径只包含ETL/Baseball目录,自然找不到上层的DataServices目录,所以触发ModuleNotFoundError。


可行解决方案

方案1:调整运行命令(最简单,无需修改代码)

不要进入Baseball目录运行脚本,切换到项目根目录ETL下,使用模块模式运行:

python -m Baseball.Baseball_DataImport

该运行方式会自动将ETL目录加入模块搜索路径,可直接识别DataServices模块。

方案2:手动添加搜索路径(适合单文件调试场景)

在Baseball_DataImport.py的所有导入语句最前方添加如下代码:

import sys
import os
# 拿到ETL根目录的绝对路径,加入模块搜索路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

添加完成后再导入DataServices相关模块即可正常识别。


附加注意事项

你当前DataService.py中的导入写法也存在相同的路径问题,解决上层导入问题后会触发新的ModuleNotFoundError,需要将DataService.py中的导入修改为相对导入或者绝对导入:

# 写法1:相对导入(仅作为包模块导入时生效,直接运行DataService.py不生效)
from . import ConfigServices
from . import PageDataModel

# 写法2:绝对导入
from DataServices import ConfigServices
from DataServices import PageDataModel

内容的提问来源于stack exchange,提问作者Brandon Michael Hunter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 21:27:03