Python 项目中解决 pytest 测试时模块导入报错的经典方案,核心是通过动态添加项目根目录到 Python 路径,配合-m pytest的模块式运行,彻底解决相对导入、路径不匹配的问题。一、代码逐行解析python运行import sys from pathlib import Path # 动态添加项目根目录到Python路径 project_root = Path(__file__).resolve().parent.parent sys.path.insert(0, str(project_root)) # insert(0) 优先级更高,避免冲突 # 正常导入 import business.common as common # 你的测试代码... def test_create_topic(): topic_data = { "accesstoken": common.get_token(), "title": "aaaa", "tab": "job", "content": "bbb" } r = common.create_topic(topic_data) print(r.status_code) print(r.