Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 error “ImportError: No module named” have __init__.py

I created a simple flask 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
..

The application.py from the src look 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

The test_myproject looks like this:

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

I use Pycharm to develop this and when I click run it works but when I try to run it via the 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'

Runnint the unittests with python -m unittest works.

If I change the imports 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 via the command line, however the tests won't work anymore.

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

What am I doing wrong?

like image 680
Denis Nutiu Avatar asked Apr 17 '17 09:04

Denis Nutiu


People also ask

How do I fix No module named error in Python?

How do i fix the no module named error in Python? We typically fix the error by adding the third party library into our development environment using the Python package installer (PIP) utility. Using PIP is relatively straightforward: Save your work and close your development environment.

What is ImportError in Python?

ImportError is raised when a module, or member of a module, cannot be imported. There are a two conditions where an ImportError might be raised. If a module does not exist.

How do you fix ModuleNotFoundError and ImportError?

Python's ImportError ( ModuleNotFoundError ) indicates that you tried to import a module that Python doesn't find. It can usually be eliminated by adding a file named __init__.py to the directory and then adding this directory to $PYTHONPATH .


1 Answers

You said that you're running python application.py, which suggests that your working directory is src. To be able to import modules under src.* (without playing with PYTHONPATH) you should run Python from the myproject directory instead.

Consider either moving application.py to myproject or running it with python src/application.py.

like image 121
Adam Byrtek Avatar answered Sep 30 '22 20:09

Adam Byrtek