Flask import problem with Python 3 and __main__.py
Terry Reedy
tjreedy at udel.edu
Tue Aug 26 14:03:26 EDT 2014
On 8/26/2014 12:03 PM, Jon Ribbens wrote:
> Flask suggests the following file layout:
>
> runflaskapp.py
> flaskapp/
> __init__.py
>
> runflaskapp.py contains:
>
> from flaskapp import app
> app.run(debug=True)
>
> flaskapp/__init__.py contains:
>
> from flask import Flask
> app = Flask(__name__)
Unless there is something else in flaskapp, this seems senseless. Why
not runflaskapp.py:
from flask import Flask
app = Flask(__name__)
app.run(debug=True)
> Running this with 'python3 runflaskapp.py' works fine.
You are either giving this in directory 'x' containing runflaskapp.py or
given a longer pathname. In either case, directory 'x' get prepended to
sys.path, so that 'import flaskapp' finds flaskapp in x.
> However it
> seems to me that a more Python3onic way of doing this would be to
> rename 'runflaskapp.py' as 'flaskapp/__main__.py'
> and then run the whole thing as 'python3 -m flaskapp'.
In what directory?
> Unfortunately this doesn't work:
Because x does not get added to sys.path.
> $ python3 -m flaskapp
> * Running on http://127.0.0.1:5000/
> * Restarting with reloader
> Traceback (most recent call last):
> File "/home/username/src/flaskapp/__main__.py", line 1, in <module>
> from flaskapp import app
> ImportError: No module named 'flaskapp'
>
> Does anyone know why and how to fix it?
Since flaskapp/__main__.py is found and run, make the change suggested
above that eliminates the flaskapp import.
Or put flaskapp in site_packages, which is on the import search path .
Pip, and I presume other installers, typically puts startup scripts in a
directory that is on the system path. For Windows, this is
pythonxy/Scripts. But this is more than I would do for most local apps.
--
Terry Jan Reedy
More information about the Python-list
mailing list