在项目中找不到模块(Python)

2024-06-17 10:51:48 发布

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

我是一个初学者,我不理解项目文件夹结构中的某些内容

我有这个项目:

.
└── convertersProject/
    ├── conftest.py -----------------> best practice if you're not using src structure
    ├── converters  -----------------> module I'm trying to import/
    │   ├── __init__.py
    │   ├── binconverter.py
    │   └── importester1.py  --------> import binconverter OR from converters import */
    │       └── submodule/
    │           ├── __init__.py -----> not needed if I don't want to use it as package
    │           └── importester2.py -> from converter import binconverter 
    ├── outsidemodule  /
    │   ├── importester3.py
    │   └── __init__.py 
    └── test /
        └── test_converters.py

当试图直接从项目文件夹执行importester1/2/3.py时,我总是收到ModuleNotErrorFound。我正在使用一个虚拟环境,使用pyenv python 3.8.5中的pyenv shell 3.8.5设置python -m venv 'name'

我认为我理解的是:

  • 我必须使用绝对路径作为from converters.binconverter import bin2dec作为binconverter中的bin2dec函数。如果我想使用relative,我应该在文件夹树中尝试执行importertest2.py,因为submoduleconverters内。所以,我不能用亲属来表示outsidemodule
  • PYTHONPATH是您正在执行的当前文件夹,因此,如果我以python converters/submodule/importester2.py的形式从项目文件夹执行,我不必向虚拟环境的PYTHONPATH附加任何值(事实上,我读到这不是一个好的做法)
  • __init__.py允许您使用模块,而无需向PYTHONPATH virtualenv追加值,因此我可以使用绝对路径importconverter模块插入outsidemodule
  • tests正在使用此逻辑工作。事实上,如果我更改了某些内容,VSCode调试器将检测import问题

我到底错过了什么


Tags: to项目frompyimport文件夹内容if