Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ''
like image 227
bytes1234 Avatar asked Jun 28 '16 22:06

bytes1234


1 Answers

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.

like image 161
Wombatz Avatar answered Oct 20 '22 19:10

Wombatz