[英]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.