python - 从外部包/文件夹导入包/脚本
问题描述
项目结构为:
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 ================================================================================
我试图将包附加到文件夹内部的src
sys 路径中,但没有成功:__init__.py
unit
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
夹中它不起作用,为什么?
解决方案
推荐阅读
- google-cloud-platform - Google Vision 并不总是在网络检测响应中包含 pagesWithMatchingImages
- amazon-web-services - 添加了 aws apigateway lambda 授权程序,出现 500 错误
- json-ld - 谷歌搜索结构化数据中允许使用哪些字符
- c - 为什么我在 C 中得到错误的平均值?
- for-loop - 初始化 for 循环计数器的成本是多少?为什么使用 int 而不是 byte?
- python - 在 Python 中,如何在创建的 csv 文件中插入一个附加字段,该文件根据查询结果对字段内容具有 elseif 条件?
- django - nginx API 跨源调用仅在某些浏览器中不起作用
- swift - 如何删除 uicollectionview 中的 sectionHeader?
- javascript - Promise 提前返回 - 带有 Promise 的映射数组
- python - 电报消息上设置的不同表情符号