测试文件中无法导入自定义Python模块的问题排查
Python模块导入问题及解决
项目结构
. ├── README.md ├── document_processing │ ├── Config.py │ ├── DocumentParser.py │ ├── FileChecker.py │ └── __init__.py ├── indexing.py └── tests ├── CheckFileTest.py └── __init__.py
测试代码实现
在tests/CheckFileTest.py中编写了针对FileChecker.py的测试代码:
import unittest from document_processing.Config import Config from document_processing.FileChecker import FileChecker class CheckFileTest(unittest.TestCase): def __init__(self): self.config = Config() self.fc = FileChecker(self.config) def test_not_empty_line(self): ... def test_line_format(self): ... if __name__ == "__main__": unittest.main()
报错情况
从项目根目录运行测试文件时,触发模块未找到错误:
Traceback (most recent call last): File "/Users/thomaslaurent/Dev/MIRCV_project/tests/CheckFileTest.py", line 3, in <module> from document_processing.Config import Config ModuleNotFoundError: No module named 'document_processing
尝试改用相对导入:
from ..document_processing.Config import Config
又出现新错误:
ImportError: attempted relative import with no known parent package
解决方法
删除tests目录下的__init__.py(不将tests设为Python包),然后在项目根目录创建setup.py文件:
from setuptools import setup setup( name="MIRCV_project", version="1.0", description="", author="Thomas LAURENT", author_email="", packages=["document_processing"], install_requires=[], # 项目依赖的外部包 )
执行以下命令,将项目以可编辑模式安装:
python -m pip install --editable .
通过setuptools将项目注册为Python可识别的包后,就能解决模块导入路径问题,让测试代码正常导入document_processing下的模块。
内容的提问来源于stack exchange,提问作者Atro_TLT
相关产品推荐
相关产品推荐

