My module has __init__.py and still Python can't import it
<p>I have a small python module </p>

<pre><code>+-- address_book
|   +-- models.py
|   +-- __init__.py 
    +-- test
    |   +-- test_models.py 
</code></pre>

<p>When I run <code>python address_book/test/test_models.py</code> I get this error </p>

<pre><code>Traceback (most recent call last):
  File "address_book/test/test_models.py", line 5, in &lt;module&gt;
    from address_book import models
ImportError: No module named 'address_book'
</code></pre>

<h1>test_models.py</h1>

<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest
from address_book import models
...
...
...
if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>The problem stems from the fact that python does not know where to look for <code>address_book</code>. You can fix this by setting the <code>PYTHONPATH</code> environment variable before starting python.</p>

<p>Given the following directory structure:</p>

<pre><code>base_dir
+-- address_book
|   +-- __init__.py 
|   +-- models.py
    +-- test
    |   +-- test_models.py
</code></pre>

<p>Then this will work:</p>

<pre><code>$ env PYTHONPATH=/path/to/base_dir python address_book/test/test_models.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
</code></pre>

<p><code>PYTHONPATH</code> can be a relative path as well, just so long as the relative path points to the source directory from the current working directory</p>

<p>To avoid typing out the <code>env PYTHONPATH=/path/to/base_dir</code> each time you can set it using your shells appropriate syntax. Below I set the PYTHONPATH environment variable using a bash syntax.</p>

<pre><code>$ cd /path/to/base_dir
$ export PYTHONPATH=. # the current directory as a relative link
$ python address_book/test/test_models.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
</code></pre>

<hr>

<p>As a side note I would alter your directory structure as it's not a great idea to keep your tests in the same directory tree as your source directory. Typically you might do something like this:</p>

<pre><code>base_dir
+-- address_book
|   +-- __init__.py 
|   +-- models.py
+-- test # no __init__, not a module
|   +-- test_models.py
</code></pre>

<p>This allows you to more easily package your project without also including your tests.</p>

python