单元测试中的Python相对导入报错问题求助
相对导入报错:ImportError: attempted relative import with no known parent package
问题背景
目录结构如下:
--src --dir1 --signal __init__.py parent_class.py --hf __init__.py child_class.py child_class_tests.py
child_class.py中使用相对导入父类:from ..parent_class import Parent- 在PyCharm中运行
child_class_tests.py时,脚本路径为C:\test\src\dir1\signal\hf\child_class_tests.py,工作目录设为C:\test\src\dir1\signal\hf\,触发报错:ImportError: attempted relative import with no known parent package - 报错发生在
child_class_tests.py执行from child_class import Child时,根源是child_class.py中的相对导入无法识别父包
解决方案
方案1:修改PyCharm运行配置的工作目录
将运行配置中的工作目录从C:\test\src\dir1\signal\hf\改为C:\test\src,让Python将src识别为顶层包目录,此时child_class.py中的相对导入能正确解析父包路径。
方案2:替换为绝对导入并配置路径
- 修改
child_class.py的导入语句为绝对路径:
from dir1.signal.parent_class import Parent
- 把
src目录标记为PyCharm的Sources Root(右键src目录 → Mark Directory as → Sources Root),PyCharm会自动将其加入Python的sys.path;或者在child_class_tests.py开头手动添加:
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../')))
方案3:以模块方式运行测试脚本
打开终端,进入src目录,执行以下命令运行测试:
python -m dir1.signal.hf.child_class_tests
这种运行方式会将src作为包根目录,相对导入可正常工作。
方案4:调整测试文件的导入逻辑
修改child_class_tests.py的导入部分,先将src加入sys.path,再用绝对导入:
import unittest import pandas as pd import sys import os # 把src目录添加到sys.path最前面 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../'))) # 用绝对路径导入Child类 from dir1.signal.hf.child_class import Child class TestSignals(unittest.TestCase): DATA = pd.read_pickle(r'data.pkl') def test_child_class(self): test_set = self.DATA.copy() print(test_set.head()) if __name__ == '__main__': unittest.main()
内容的提问来源于stack exchange,提问作者StormsEdge
相关产品推荐
相关产品推荐

