Py学习  »  Python

未找到python模块,相对文件夹。不明白

Gibbo • 5 年前 • 1301 次点击  

在谷歌上有无数的答案,但我似乎无法应用任何修复程序并获得预期的结果!希望有人能帮我?

我以前使用过python,但是已经有一段时间了,我从去年开始用sqlacalchemy和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文件,在这里我有我的sqlachemy引擎/会话工厂。这是我的测试文件找不到的文件。

# 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,而不是context,但仍然没有。 最初我在访问models.py时遇到了这个问题,但那是因为我忘记了 初始化 .py在文件夹中!

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38310
 
1301 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Nafees Anwar
Reply   •   1 楼
Nafees Anwar    6 年前

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

from context import Session

但失败了。正如从基本目录执行一样,可以使用

from tests.context import Session

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

from .context import Session
nicktids
Reply   •   2 楼
nicktids    6 年前

一个快速的方法来防止你把头发扯下来

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