首页 > 解决方案 > 从外部包/文件夹导入包/脚本

问题描述

项目结构为:

src/
├---__init__.py
└---domain/
    ├---__init__.py
    ├---model/
    |   ├---__init__.py
    |   └---model_mapper.py
    └---util/
        ├---__init__.py
        └---utils.py
test/
├---__init__.py
└---unit/
    ├---__init__.py
    └---test_model_mapper.py

当我pytest从父文件夹运行时,src出现以下错误:

==================================================================================== ERRORS =====================================================================================
________________________________________________________________ ERROR collecting test/unit/test_model_mapper.py ________________________________________________________________ 
ImportError while importing test module 'D:\asant\Desktop\error-repo\test\unit\test_model_mapper.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
c:\users\asant\appdata\local\programs\python\python37\lib\importlib\__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
test\unit\test_model_mapper.py:1: in <module>
    from model.model_mapper import ModelMapper
E   ModuleNotFoundError: No module named 'model'
============================================================================ short test summary info ============================================================================ 
ERROR test/unit/test_model_mapper.py
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
=============================================================================== 1 error in 0.10s ================================================================================ 

我试图将包附加到文件夹内部的srcsys 路径中,但没有成功:__init__.pyunit

import sys
import os
sys.path.append(os.path.abspath('../src'))

是重现此问题的 repo

编辑1:

我将 sys 附加代码修复为:

import sys
import os
sys.path.append(os.path.abspath('./src'))

所以把它放在里面test_model_mapper.py让我导入model包。如果我把它放在__init__.py文件unit夹中它不起作用,为什么?

标签: pythonimportpackagepytestimporterror

解决方案


推荐阅读