Python3 error "ImportError: No module named" is __init__.py

I created a simple flash application and my directory structure looks like this:

myproject
- src
-- models
--- __init__.py
-- views
--- errors.py
--- default.py
-- application.py
-- config.py
-- __init__.py
- test
-- test_myproject.py
Readme.md
setup.py
..

      

application.py from src looks like this:

from src.models import db
from src.views.errors import error_pages
from src.views.scoreboard import scoreboard
from src.config import config

      

test_myproject looks like this:

from src.models import db, Result
from src.application import create_app

      

I am using Pycharm to develop it and when I press run it works, but when I try to run it via command line python application.py

I get the following error:

Traceback (most recent call last):
  File "src/application.py", line 18, in <module>
    from src.models import db
ImportError: No module named 'src'

      

Run unittests with python -m unittest

.

If I change the import from application.py to:

from models import db
from views.errors import error_pages
from views.scoreboard import scoreboard
from config import config

      

It will work when I run it through the command line, however the tests will no longer work.

File ".../src/application.py", line 18, in <module>
    from models import db
ImportError: No module named 'models'

      

What am I doing wrong?

+3


source to share


1 answer


You said you were using python application.py

, which tells you what your working directory is src

. To be able to import modules under src.*

(without reproducing with PYTHONPATH), you must run Python from the directory myproject

.



Consider either moving application.py

to myproject

or starting it with python src/application.py

.

0


source







All Articles