0

I tried to start a Flask application with app.run() in python shell. When I passed debug=False, it worked, but not working with debug=True which gave me the following python error:

>>> from HelloW import app
>>> app.run(debug=True, port=1234)
 * Serving Flask app 'HelloW' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
C:\Users\lfcta\Documents\Python\python.exe: can't find '__main__' module in 'E:\\Flask\\Flask_WTF'

where E:\Flask\Flask_WTF\Hellow.py contains the following code:

from    flask   import Flask

app = Flask(__name__)

@app.route('/home')
def home():
    return '<h2>Hello World!</h2>'

I don't encounter this problem with the "flask run" command regardless of the debug mode.

E:\Flask\Flask_WTF>set flask_app=HelloW.py

E:\Flask\Flask_WTF>set flask_debug=1
E:\Flask\Flask_WTF>flask run // working

E:\Flask\Flask_WTF>set flask_debug=0
E:\Flask\Flask_WTF>flask run // working
 
Leon Chang
  • 669
  • 8
  • 12

1 Answers1

1

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 "" (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 disable the reloader by setting debug to False (which is also the default):

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

Rajarshi Ghosh
  • 452
  • 1
  • 9
  • 1
    Thanks, no wonder "flask run" has no such issue as you have to "set flask_app=HelloW.py". But I just found out that you still can set debug on in python shell with [reload off](https://stackoverflow.com/questions/25504149/why-does-running-the-flask-dev-server-run-itself-twice/25504196#25504196) like `app.run(debug=True, use_reloader=False)` which is same as `flask run --debugger --no-reload`. – Leon Chang Mar 09 '22 at 03:30
  • During code development, automatic reload with "flask run" is such a nifty feature that makes Python shell's manual module reload look cumbersome, – Leon Chang Mar 19 '22 at 03:05