Lebs Lebs - 2 years ago 143
Python Question

Python package No module ImportError

Environment: Ubuntu 14

The structure:

├── a
│   ├── a.py
│   └── __init__.py
├── b
│   ├── b.py
│   └── __init__.py
└── __init__.py

In "b.py":

import test.a.a

if I run "python b.py":

Traceback (most recent call last):
File "b.py", line 1, in <module>
import test.a.a
ImportError: No module named a.a

Answer Source

you have several options

1) Include the path to the folder test to sys.path

you can do hardcoded


import sys
import test.a.a

but in this case you have to change it manually if later you change the test folder to another place

you can also do automatic with


import os, sys
path = os.path.dirname( os.path.dirname( os.path.dirname(__file__) ) )
#       folder_of_test/     test      /           b
import test.a.a

in this one, if you are using python 2 you need to call os.path.abspath on __file__ first

2) Add the test's parent folder to your PYTHONPATH environment variable, or put the test folder in a folder in your PYTHONPATH or PATH environment variable.

to do this do

$> export PYTHONPATH="/path/to/parent/folder/of/test:$PYTHONPATH"

but most likely will only be temporal, to do in a permanent way go to the file .profile or .bashrc in your home folder and put the above instruction in there at the end in your favorite way (I modify .profile to set my pythonpath)

3) Call your code as python -m test.b.b from the folder that contain test

in any case you have to make sure that you don't other library that have the same name, for example I have anaconda installed and that come with a test package, and in that case you should change the name to avoid confusion

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download