Tuesday 24 May 2016

python - Ubuntu does not find module directory containing __init__.py



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?


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...