Python模块导入问题subdi

2024-04-25 02:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Python3项目中有以下目录结构:

├── README.md
├── requirements.txt
├── schemas
│   ├── collector.sql
│   └── controller.sql
├── src
│   ├── controller.db
│   ├── controller.py
│   ├── measurement_agent.py
├── tests
│   ├── regression.py
│   ├── test-invalid-mac.py
│   ├── test-invalid-url.py
│   ├── test-register-ma-json.py
│   ├── test-register-ma-return-code.py
│   ├── test-send-capabilities-return-code.py
│   ├── test-valid-mac.py
│   └── test-valid-url.py
└── todo

在我的tests文件夹中,我有一些回归测试,运行这些测试是为了检查src/measurement中代码的一致性_代理.py. 现在的问题是,我不想将度量值手动添加到我的路径中_代理.py从中获取信息。我想知道是否有什么诀窍可以告诉Python在我的根目录中查找我试图使用的导入。你知道吗

目前我正在做:

import os.path

ma = os.path.abspath('..') + '/src'
sys.path.append(ma)

from measurement_agent import check_hardware_address

会想要像这样的东西

from measurement_agent import check_hardware_address

不使用任何操作系统路径诡计。你知道吗

有什么建议吗?你知道吗


Tags: pathpytestimportsrcregisterurlsql
1条回答
网友
1楼 · 发布于 2024-04-25 02:24:19

相对进口

  1. 确保所有文件夹中都有__init__.py,包括最上面的文件夹(父文件夹)
  2. 使用相对导入,如下所示:

    from ..src import measurement_agent

  3. 现在运行您的代码,cd到父目录的父目录,然后

    python -m parent.test.regression

相关问题 更多 >