繁体   English   中英

未找到 Python 模块,相关文件夹。 想不通

[英]Python Module not found, relative folder. Can't figure it out

谷歌上有一百万个答案,但我似乎无法应用任何修复并获得预期的结果! 希望有人能在这里帮助我?

我过去使用过 Python,但已经有一段时间了,我正在使用 SQLAlchemy 和 SQLite3 重写去年的旧项目。

问题是,我似乎无法让我的测试顺利进行。 我试图将我的测试数据库与生产数据库分开,所以我有以下文件结构:

    .
├── fleet_manager
│   ├── controller
│   │   └── customer_controller.py
│   ├── database.db
│   ├── fleet_manager.py
│   ├── model
│   │   ├── __init__.py
│   │   ├── models.py
│   └── view
├── Pipfile
├── Pipfile.lock
└── tests
    ├── context.py
    ├── __init__.py
    ├── test_customer_controller.py
    ├── test.db
    └── test_models.py

所以我创建了一个 context.py 文件,在这里我有我的 SQLAlchemy 引擎/会话工厂。 我的测试文件找不到这个文件。

# test_models.py

from mamba import description, context, it, before
from expects import expect, equal, be_a, be_none
from sqlalchemy import create_engine, Table
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker


from context import Session # < this mofo here
from fleet_manager.model.models import (
    Equipment,
    EquipmentType,
    Discipline,
    Size,
    Make,
    Model,
    Customer,
    Base)

所以基本上上面的文件根本没有找到上下文

# context.py

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

engine = create_engine('sqlite:///tests/test.db', echo=True)
Session = sessionmaker(bind=engine)

这是我得到的错误(省略了多余的跟踪):

ModuleNotFoundError: No module named 'tests/test_models'

到目前为止,我已经尝试了很多东西。 我已经尝试使用 os.path 修改路径,以及使用 .context 而不是上下文,但仍然没有。 最初我在尝试访问我的 models.py 时遇到了这个问题,但那是因为我忘记将init .py 放在文件夹中!

有人能帮我一下吗? 扯掉我的头发。

一种让你免于扯掉头发的快速方法

import sys
sys.path.append("/path/to/your/package_or_module")

问题是您的测试目录不在您的 python 路径中。 它不会是默认的。 您正在尝试使用从该目录导入

from context import Session

它失败了。 正如您将从基本目录执行一样,您可以使用从该目录进行绝对导入

from tests.context import Session

或者像这样使用相对导入。

from .context import Session

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM