1

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?

asked Jul 20, 2017 at 7:50
1
  • First, don't skip src in the import (project . src . utils). Second, you probably need to turn project and src into packages (place __init__.py there). Third, I'm not sure if relative imports beyond the top-level module will work, so you may need to put project in the python search path. Commented Jul 20, 2017 at 7:56

1 Answer 1

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
answered Jul 20, 2017 at 7:58
Sign up to request clarification or add additional context in comments.

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'
At the very beginning of main.py please do: import sys; print sys.path - we'll see if it doesn't see the utils dir, or you have wrong file layout
sys.path contains '/home/user/project/src/app1". All other folders are system folders from the virtual environment.
Fair enough. Editing the answer, I'll change the approach a bit - we're gonna move utils to app1 package. See if it works now.
That works. But my wish is to maintain the utils in src since I plan to bring more apps into this project which will need the utils.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.