You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Poetry时如何在测试文件中正确导入my_pkg包?

解决ModuleNotFoundError: No module named 'my_pkg'的问题

针对你的项目结构,有几种靠谱的解决方法:

  • 用Poetry直接运行测试
    不用手动处理路径,直接在项目根目录执行命令:

    poetry run python tests/test.py
    

    如果用pytest框架,直接运行:

    poetry run pytest tests/test.py
    

    Poetry会自动把src目录加入Python路径,确保my_pkg能被找到。

  • 先安装本地包到虚拟环境
    在项目根目录执行:

    poetry install
    

    这个命令会把src下的my_pkg以可编辑模式安装到Poetry创建的虚拟环境中,之后只要激活虚拟环境(poetry shell)再运行测试文件,就不会出现模块找不到的问题。

  • 临时手动添加路径(不推荐)
    如果只是临时测试,可以在test.py开头添加代码,把src目录加入Python的路径列表:

    import sys
    from pathlib import Path
    
    # 把项目根目录下的src文件夹添加到路径
    sys.path.append(str(Path(__file__).parent.parent / "src"))
    
    import my_pkg
    

    这种方法依赖路径硬编码,团队协作或环境变化时容易出问题,优先用前两种方法。

内容的提问来源于stack exchange,提问作者Harry Stuart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:07:02