我在“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/