bash 烧瓶教程疑难解答:ModuleNotFoundError: No module named 'app'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43335289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
flask tutorial troubleshooting: ModuleNotFoundError: No module named 'app'
提问by Cora Coleman
I am having trouble running my run.py file. My file structure looks like this:
我在运行 run.py 文件时遇到问题。我的文件结构如下所示:
With another python file called 'run.py' located in flask/bin along with python3. My run.py file is simply:
另一个名为“run.py”的python文件与python3一起位于flask/bin中。我的 run.py 文件很简单:
#!flask/bin/python3
from app import app
app.run(debug=True)
However running 'python3 run.py' throws the error:
但是,运行“python3 run.py”会引发错误:
$ python3 run.py
Traceback (most recent call last):
File "run.py", line 2, in <module>
from app import app
ModuleNotFoundError: No module named 'app'
app.py looks like:
app.py 看起来像:
from flask import Flask
app = Flask(__name__)
from app import views
I am confused about how to solve this as I have been messing with the directories such as putting app.py into the flask/bin folder and putting it outside of all folders shown in my directory above, but these methods have not worked for me.
我对如何解决这个问题感到困惑,因为我一直在搞乱目录,例如将 app.py 放入烧瓶/bin 文件夹并将其放在我上面目录中显示的所有文件夹之外,但这些方法对我不起作用。
回答by Achim Munene
your run.py is not able to import app as it can not see app within the bin folder, what happens with python is that all python files are treated as modules and the folders with an init.py file are treated as packages so run.py will start looking for the app package to import the app module however it will search within the bin directory. Read through Python documentationto fully understand the modules and packages. for now you might want to reorganize your application directory to look like this:
您的 run.py 无法导入应用程序,因为它在 bin 文件夹中看不到应用程序,python 发生的情况是所有 python 文件都被视为模块,而带有init.py 文件的文件夹被视为包,因此运行。 py 将开始寻找应用程序包以导入应用程序模块,但它将在 bin 目录中搜索。通读Python 文档以全面了解模块和包。现在你可能想要重新组织你的应用程序目录,如下所示:
dir app
file app.py
dir flask
file run.py
By ensuring that run.py and app directory are at the same level in the directory run.py will be able to import from app now.
通过确保 run.py 和 app 目录在目录 run.py 中处于同一级别,现在可以从 app 导入。
I hope that helps
我希望有帮助