Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
856 views
in Technique[技术] by (71.8m points)

python flask can't find '__main__' module in ''

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 ''
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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!

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 ''

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...