python - VSCODE PYTHON - ModuleNotFoundError : No module named 'src'

标签 python visual-studio-code python-import importerror src

我在“cmd”中使用 pytest 进行了单元测试,它工作正常,但是当我尝试导入我的主文件时,出现导入错误。这是我的文件树结构:

MATCHING_CC/
- pytest.ini
- __init__.py               (empty file)
- conftest.py               (empty file)
- src/
    - __init__.py           (empty file)
    - conftest.py           (empty file)
    - matching_ingr_zing.py
    - services/
        - __init__.py       (empty file)
        - ElasticSearch.py
        - ingredient_extractor_for_search.py
        - metrics.py
        - stop_word_matching.py
- models/        (folder to save trained models)
- tests/
    - __init__.py                (empty file)
    - test_services/
        - __init__.py            (empty file)
        - test_elastic_search.py
        - test_ingredient_extractor_for_search.py
        - test_metrics.py
    - test_src/
        - __init__.py                (empty file)
        - test_matching_ingr_zingr.py

这是问题的图像: error

如果有人可以帮助我并解释我的错误是什么,我将不胜感激。

最佳答案

您的程序似乎不知道在哪里定位src。这可能会解决问题。

import sys
  
# adding src to the system path
sys.path.insert(0, '/home/USERNAME/PATH/TO/src')
  
from src import something

这里有一个解释:

ModuleNotFoundError, because by default python interpreter will check for the file in the current directory only, and we need to set the file path manually to import the modules from another directory. We can do this using various ways. These ways are discussed below in detail.

Using sys module

We can use sys.path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that python can also look for the module in that directory if it doesn’t found the module in its current directory. As sys.path falls under the list type class so, we can easily use the insert method to add the folder path.

进一步阅读: https://www.geeksforgeeks.org/python-import-module-from-different-directory/

关于python - VSCODE PYTHON - ModuleNotFoundError : No module named 'src' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72898785/

相关文章:

python - Spacy无法安装在使用pypy创建的virtualenv中

visual-studio-code - 即使 "files.insertFinalNewline"设置为 true,VS Code 也不会插入最后的新行

Python:强制每个导入重新加载

visual-studio-code - Visual Studio代码在保存扩展上运行未运行

visual-studio-code - 如何在 VSCode 中从 "format on save"中排除文件扩展名和语言?

python - 在 python 中导入模块的最 pythonic 方法是什么

Python包导入问题

python - PyQT5 QGIS 对话框交互

python - 如何使用作为参数传递的行号拆分csv文件并保存到不同的文件中

python - 分隔某些列中具有相同值的行