【问题标题】:ModuleNotFoundError: No module named 'utils': How do I change the parent directory looked at by ImportModuleNotFoundError: No module named 'utils': 如何更改 Import 查看的父目录
【发布时间】:2021-03-17 10:22:12
【问题描述】:

我想我知道这里的问题是什么,但我不知道如何解决它。这是我在项目目录中的当前结构:

└── src
    ├── utils
       └── utils.py
    ├── comparator
       └── comparatorclass.py

在我的comparatorclass.py 中,我有以下导入语句:

from utils.logging_service import LoggingService
from utils.utils import Utils

当我运行comparatorclass.py 时,我得到了错误

Traceback (most recent call last):
  File "comparator_gui.py", line 11, in <module>
    import comparatorclass
  File "/Users/sidu/Desktop/aaababa/src/comparator/comparatorclass.py", line 16, in <module>
    from utils.logging_service import LoggingService
ModuleNotFoundError: No module named 'utils'

当然,我很确定发生的事情是comparatorclass.py 正在比较器目录中寻找utils 目录,而实际上它位于该目录之上。当我有这样的结构时,代码可以工作:

└── src
    ├── utils
       └── utils.py
    ├── comparatorclass.py

这是有道理的,因为现在它能够在同一个父目录 src 中找到 utils 目录。我的问题是如何让它与第一个场景一起工作?我需要一种方法来更改导入语句所查看的父目录。

【问题讨论】:

标签: python python-import importerror python-module modulenotfounderror


【解决方案1】:

我通过在导入实用程序之前添加以下行解决了这个问题:

sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..'))  

from utilities.logging_service import LoggingService
from utilities.comparator_utils import Utils

我不知道这是否是正确的解决方案,但它确实为我解决了问题。

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2021-09-10
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 2014-07-30
    • 1970-01-01
    相关资源
    最近更新 更多