终端运行Python脚本报ece_prm_agent模块不存在但IDE运行正常
问题解决方法
根本原因
IDE运行代码时会自动将项目根目录/Users/rgupta75/github/ece-prm添加到Python的模块搜索路径中,而终端直接执行脚本时,默认仅将脚本所在的/Users/rgupta75/github/ece-prm/deploy目录加入搜索路径,因此无法找到根目录下的ece_prm_agent包。
可行解决方案
- 方案1:临时指定PYTHONPATH执行(无需改代码)
执行命令时提前声明项目根目录为模块搜索路径即可,修改后的运行命令如下:PYTHONPATH=/Users/rgupta75/github/ece-prm /Users/rgupta75/github/ece-prm/.venv/bin/python -s /Users/rgupta75/github/ece-prm/deploy/hcc_k8_deploy.py stage - 方案2:脚本内手动添加搜索路径(一劳永逸,任意位置执行都生效)
在导入ece_prm_agent相关逻辑之前,添加如下代码将项目根目录加入搜索路径:
修改后的完整代码片段参考:import sys from pathlib import Path # 自动计算项目根目录(当前脚本父目录的父目录) sys.path.append(str(Path(__file__).parent.parent.resolve()))import sys, os, requests, subprocess, json from pathlib import Path # requires python 3.4+ # 新增:添加项目根目录到模块搜索路径 sys.path.append(str(Path(__file__).parent.parent.resolve())) os.environ["env"] = "local" from ece_prm_agent.utils.cyberark.cyberark import cyberark - 方案3:将项目安装到虚拟环境(适合长期开发场景)
进入项目根目录,执行如下命令将当前项目以可编辑模式安装到虚拟环境中,之后无需额外配置即可直接导入项目内的包:cd /Users/rgupta75/github/ece-prm .venv/bin/pip install -e .
内容的提问来源于stack exchange,提问作者bosari
相关产品推荐
相关产品推荐

