ModuleNotFoundError:没有名为{directory}的模块

2024-05-19 01:05:47 发布

您现在位置:Python中文网/ 问答频道 /正文

当我调用/Users/rgupta75/github/ece-prm/.venv/bin/python -s /Users/rgupta75/github/ece-prm/deploy/hcc_k8_deploy.py stage时,我收到一个错误-

ModuleNotFoundError: No module named 'ece_prm_agent' line 4, in

这是我的代码片段

import sys, os, requests, subprocess, json
from pathlib import Path # requires python 3.4+
os.environ["env"] = "local"
from ece_prm_agent.utils.cyberark.cyberark import cyberark

下面是我的文件夹结构图-

enter image description here

令人惊讶的是,当从IDE运行时,它可以正常工作,但不能从终端运行


Tags: fromimportgithubbinvenvosusersdeploy
1条回答
网友
1楼 · 发布于 2024-05-19 01:05:47

该错误意味着在sys.path中找不到模块ece_prm_agent。它可能在您的IDE上工作,因为它是从当前目录ece-prm本身执行的,而当前目录documented是允许的:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

假设这是您的文件树

$ tree
.
├── deploy
│   └── hcc_k8_deploy.py  # Let's say this just calls cyberark.py::cyberark()
└── ece_prm_agent
    └── utils
        └── cyberark
            └── cyberark.py  # Let's say this just prints "Success"

从目录本身运行它将成功运行

$ pwd
/home/nponcian/Documents/ece-prm
$ python3 deploy/hcc_k8_deploy.py 
Success!

而在外部运行它会失败

$ pwd
/home/nponcian
$ python3 /home/nponcian/Documents/ece-prm/deploy/hcc_k8_deploy.py
Traceback (most recent call last):
  File "/home/nponcian/Documents/ece-prm/deploy/hcc_k8_deploy.py", line 1, in <module>
    from ece_prm_agent.utils.cyberark.cyberark import cyberark
ModuleNotFoundError: No module named 'ece_prm_agent'

如上面的文档所述,您应该设置PYTHONPATH,以便Python可以找到相对于ece-prm的导入模块

$ export PYTHONPATH=/home/nponcian/Documents/ece-prm/
$ python3 /home/nponcian/Documents/ece-prm/deploy/hcc_k8_deploy.py 
Success!

或者如果您想在Python文件ece-prm/deploy/hcc_k8_deploy.py中执行此操作

from pathlib import Path
import sys
sys.path.append(str(Path(__file__).parent.parent))
...

相关问题 更多 >

    热门问题