I am trying to set up a new Python project with the following structure:
project:
src:
app1:
main.py
utils:
__init__.py
utils1:
__init__.py
utils1.py
tests:
I would like to import utils1 in main.
I tried the following from main.py but it does not work:
main.py
from project.src.utils.utils1 import utils1
This indicates the following error:
(virtualenv)user: /home/user/project/src/app1 $ python main.py
ImportError: No module named 'project'
How can I import utils1 in main correctly?
1 Answer 1
There is no __init__.py in project directory, so project isn't recognised as a package. The same goes with src directory.
Besides, you're running from app1 directory, so directories above it aren't visible in pythonpath.
Change directory to ~/project/src, move utils directory to app1, run ./app1/main.py and import app1.utils.utils1.utils1
In the end:
Your layout should look like:
project:
src:
app1:
main.py
utils:
__init__.py
utils1:
__init__.py
utils1.py
tests:
Execute as:
(virtualenv)user: /home/user/project/src $ python ./app1/main.py
And import as:
from app1.utils.utils1 import utils1
6 Comments
(virtualenv) user:/home/user/project/src $ python ./app1/main.py Traceback (most recent call last): File "./app1/main.py", line 1, in <module> from utils.utils1 import utils1 ImportError: No module named 'utils'
srcin the import (project . src . utils). Second, you probably need to turnprojectandsrcinto packages (place__init__.pythere). Third, I'm not sure if relative imports beyond the top-level module will work, so you may need to putprojectin the python search path.