0

I have a python project with the following structure:

/project
  /bin  
     executable      
  /app  
     __init__.py
     a.py
     b.py
     c.py

From within the /project directory I try to run the executable, which depends on modules in the app package:

./bin/executable

However, when I try this, python fails to find any modules defined in the app package, giving the ImportError: No module named XYZ error.

From what I understood, the presence of __init__.py in the app directory should mark it as a module?

What am I doing wrong?

duncanhall
  • 11,035
  • 5
  • 54
  • 86
  • This might be of help http://stackoverflow.com/questions/9427037/relative-path-not-working-even-with-init-py – danidee Feb 16 '16 at 10:29
  • Thanks, it doesn't. I shouldn't need to add a directory to path/pythonpath if that directory already has an `__init__.py' file inside? – duncanhall Feb 16 '16 at 10:32

1 Answers1

1

If you add the following to your executable (before you try importing your app module):

import sys; print sys.path
...
import app

You'll see that the current working directory is not included in the path. I suggest you create a proper Python package by adding a setup.py file. You can then install your package and your executable should work just fine.

Here is a simple setup.py file:

from setuptools import find_packages, setup

config = {
    'name': 'app',
    'version': '0.1.0',
    'description': 'some app',
    'packages': find_packages(),
}

setup(**config)

I prefer to install into a virtualenv:

virtualenv venv
source venv/bin/activate
python setup.py install
./bin/executable

Now, if you deactivate that virtualenv and try running your executable again, you will get your original ImportError.

Take a few minutes and read through the Python Packaging User Guide.

Also, you might want to use python setup.py develop instead of python setup.py install.

jamesdarabi
  • 280
  • 1
  • 3
  • 13