尝试从目录外部导入时出现ModuleNotFoundError [英] ModuleNotFoundError when attempting to import from outside of directory
问题描述
我正在开发Flask应用,并尝试运行我的测试文件,但无法运行.我当前的应用程序结构为:
I'm working on a Flask app and attempting to run my test file but unable to do so. My current app structure is:
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
当我尝试从 test_user_model.py
中的app.models import User 运行时,它会引发
ModuleNotFoundError:没有名为"app"的模块
.我尝试了无数种不同方式来编辑导入语句,但是在每种情况下仍然会引发错误(<.app导入模型中的
超出范围, import app
等导入也不起作用.)
when I attempt to run from app.models import User
in test_user_model.py
it raises ModuleNotFoundError: No module named 'app'
. I've tried editing the import statement countless different ways but it still raises an error in every case (from ..app import models
is out of scope, import app
and similar imports also don't work.)
推荐答案
您应在 tests
目录中添加 __ init __.py
.空的 __ init __.py
将把该目录变成一个包.然后,您可以在 test_user_model.py
中使用这一行:
You should add __init__.py
in your tests
directory. The empty __init__.py
will turn that directory into a package. Then you can use this line in your test_user_model.py
:
from app.models import User
在 PEP 328 中查看详细信息.
这篇关于尝试从目录外部导入时出现ModuleNotFoundError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!