Without Me It Just Aweso
Without Me It Just Aweso

Reputation: 4883

python module importing difficulties

Im relatively new to python so forgive me if this is fundamental.

I have a directory where I have my main applicatino code , in a file app.py . I then have a sub directory Model which contains the required __init__.py file, and backend.py

in app.py when I try to import model.backend I get an ImportError: no module named model.backend

However if in the same directory that app.py lives I drop into a python shell and type import model.backend it works. Why? Why can I import it in the shell but not in my application?

Edit: My directory structure looks like

src/
`- myapp
   +- __init__.py
   +- app.py
   `- model/
      +- __init__.py
      `- backend.py

Thanks

Upvotes: 0

Views: 172

Answers (2)

andrew cooke
andrew cooke

Reputation: 46872

do you have this structure?

src/
`- myapp
   +- __init__.py
   +- app.py
   `- model/
      +- __init__.py
      `- backend.py

in particular, check that there are __init__.py in both places.

if so, then PYTHONPATH=..../src (replace .... with the correct path) and

from myapp.model import backend

should work correctly.

the reason your interactive shell works is that the current directory is automatically added to PYTHONPATH.

[edit: changed Model to model]

you are making a mistake somewhere. check everything again. what i described above works (the pyc files are generated by python - ignore them):

> tree myapp/
myapp/
├── app.py
├── __init__.py
├── __init__.pyc
└── model
    ├── backend.py
    ├── backend.pyc
    ├── __init__.py
    └── __init__.pyc

1 directory, 7 files
> cat myapp/app.py

from myapp.model import backend

> cat myapp/model/backend.py

print "importing backend"

> PYTHONPATH=. python -m myapp.app
importing backend
> python -m myapp.app
importing backend

(you don't even need PYTHONPATH above since you're already running at exactly the right level).

Upvotes: 1

rdodev
rdodev

Reputation: 3202

In myapp/__init__.py you can add:

import sys
sys.path.insert(1, '.')

Upvotes: 1

Related Questions