1

I have reviewed most of the similar question here. I'm new to python and I'm using Ubuntu 13.10 The project structure is

├── projecttest
│   ├── api.py
│   ├── controller
│   │   ├── controller.py
│   │   ├── controller.pyc
│   │   ├── init_db.py
│   │   ├── __init__.py
│   │   ├── __init__.pyc
│   │   ├── settings.py
│   │   ├── settings.pyc
│   │   └── extra
│   │       ├── extra.py
│   │       ├── extra.pyc
│   │       ├── __init__.py
│   │       └── __init__.pyc
│   ├── __init__.py
│   ├── lib
│   │   └── __init__.py
│   ├── models
│   │   ├── documents.py
│   │   ├── documents.pyc
│   │   └── __init__.py

All the __init__.py files are empty (no hidden characters) and when I'm trying

$ python init_db.py

that has:

from projecttest.models.documents import *

I'm getting:

Traceback (most recent call last):
  File "controllers/init_db.py", line 1, in <module>
    from projecttest.models.documents import *
ImportError: No module named projecttest.models.documents
Farok Ojil
  • 664
  • 1
  • 12
  • 22
  • Is the directory containing `projecttest` added to `sys.path`? – Martijn Pieters Apr 07 '14 at 17:43
  • 2
    If you want packages to work, you will have to start the script from the root of the package. So if your package is at `/something/projecttest`, then you will have to start a script in `/something` to make the package names work the way you use them. – poke Apr 07 '14 at 17:47
  • @MartijnPieters I tried to add it using [this](http://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath) and [this](http://www.johnny-lin.com/cdat_tips/tips_pylang/path.html) but still doesn't work – Farok Ojil Apr 07 '14 at 18:05
  • @poke: The OP is using an absolute import form `projecttest.models.documents`; it doesn't matter here that the script itself is not part of the package namespace. – Martijn Pieters Apr 07 '14 at 18:07
  • @MartijnPieters My suggestion will still work though. – poke Apr 07 '14 at 18:09
  • @poke: sure, because the local directory of a script is part of the `sys.path` automatically. But your assertion that you *have to start the script from the root of the package* is not true. – Martijn Pieters Apr 07 '14 at 18:10

1 Answers1

0

You need to specify PYTHONPATH environment variable, it augments the default search path for module files.

It helps to think about PYTHONPATH as an absolute path. If you specify it you may import modules within your program relative to PYTHONPATH.

In your case it would be something like the following line:

PYTHONPATH=/<dir>/<folder>/projecttest/ python init_db.py

Then you may import modules without problems like:

from models.documents import *
Konstantin
  • 2,937
  • 10
  • 41
  • 58