python flask在''中找不到'__main__'模块 [英] python flask can't find '__main__' module in ''

查看:350
本文介绍了python flask在''中找不到'__main__'模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习烧瓶.我用pip来安装它.然后,当我运行此基本代码时,我得到一个错误.基本上,我看到它的工作,然后突然退出,并出现以下错误.这可能看起来是一些环境问题,但我不确定.前天这很奇怪,现在却行不通.

Hi All I am just learning about flask. I have used pip to install it. Then when I run this basic code I get an error. Basically I see its working then abruptly exits with the following error. This maybe looks to be some environment issue but I'm not sure. The strange thing this was working the other day now it's not.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'


if __name__ == '__main__':
    app.run(debug=True, port=8000, host='0.0.0.0') 

 * Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)
 * Restarting with stat
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3: can't find '__main__' module in ''

推荐答案

您说过,仅当您从交互式shell运行代码时,才会出现此问题.这是由werkzeug中的一项功能引起的(wsgi服务器flask基于该功能).

You said, that the problem only occurs when you run the code from an interactive shell. It is caused by a feature in werkzeug (the wsgi server flask is based on).

在调试模式下,如果更改了项目文件,则werkzeug将自动重新启动服务器.每次检测到更改时,werkzeug都会重新启动最初启动的文件.甚至第一个开始都是通过文件名

In debug mode werkzeug will automatically restart your server if a project file is changed. Everytime a change is detected werkzeug restarts the file that was initially started. Even the first start is done via the file name!

但是在交互式外壳程序中根本没有文件,并且werkzeug认为您的文件名为""(空字符串).然后,它尝试运行该文件.由于某些原因,它还认为""是指软件包.但是由于该软件包不存在,因此它也不能具有__main__模块,因此会出现错误.

But in the interactive shell there is no file at all and werkzeug thinks your file is called "" (empty string). It then tries to run that file. For some reason it also thinks that the "" refers to a package. But since that package does not exist it also cannot have a __main__ module, hence the error.

您可以通过直接运行""来模拟该错误

You can simulate that error by running "" directly

python ""
# prints: can't find '__main__' module in ''

您可以通过将debug设置为False(这也是默认值)来尝试禁用重新加载器:

You could try to disabe the reloader by setting debug to False (which is also the default):

app.run(debug=False, ...)

然后,它也应该在交互式会话中运行.但是,为什么要这样做呢?只需放入一个文件并运行它即可.

Then it should also run in an interactive session. But why would you do that? Just put in a file and run that.

这篇关于python flask在''中找不到'__main__'模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆