[英]python : `moduleNotFoundError` when attempting to import file from a directory
[英]ModuleNotFoundError when attempting to import from outside of directory
我正在使用Flask應用程序並嘗試運行我的測試文件但無法執行此操作。 我目前的應用結構是:
Project
── app
│ ├── __init__.py
│ ├── forms.py
│ ├── model.py
│ ├── models.py
│ ├── static
│ │ ├── css
│ │ ├── fonts
│ │ ├── img
│ │ ├── js
│ │ └── uploads
│ ├── templates
│ │ ├── client
│ │ │ ├── client-base.html
│ │ │ ├── client-inventory.html
│ │ │ ├── client-login.html
│ │ │ ├── client-macros.html
│ │ │ ├── client-main.html
│ │ │ └── client-signup.html
│ │ └── user
│ │ ├── user-base.html
│ │ ├── user-macros.html
│ │ └── user-main.html
│ └── views
│ ├── __init__.py
│ ├── client.py
│ └── user.py
├── config.py
├── run.py
└── tests
└── test_user_model.py
當我嘗試from app.models import User
運行from app.models import User
test_user_model.py
它會引發ModuleNotFoundError: No module named 'app'
。 我已經嘗試過編輯import語句無數種不同的方法,但它仍然會在每種情況下引發錯誤( from ..app import models
超出范圍, import app
和類似的導入也不起作用。)
您應該在tests
目錄中添加__init__.py
。 空的__init__.py
會將該目錄轉換為包。 然后你可以在test_user_model.py
使用這一行:
from app.models import User
詳見PEP 328 。
您需要在PYTHONPATH
添加app
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.