15

I have a python application like this

/
/crawl.py
/crawl/__init__.py
/crawl/john.py
/tests/test_john.py

What I am trying to do, is run the unit test test_john.py which needs to use john.py but it's in another folder.

In my tests/test_john.py I get this when I run it

Traceback (most recent call last):
  File "test_john.py", line 2, in <module>
    from john import John
ImportError: No module named john

So how can I import a class, from the crawl folder....

David Z
  • 128,184
  • 27
  • 255
  • 279
Wizzard
  • 12,582
  • 22
  • 68
  • 101
  • you could try `from crawl.john import John` or try `from ..crawl.john import John` (refer http://stackoverflow.com/questions/1054271/how-to-import-a-python-class-that-is-in-a-directory-above) – Sandip Agarwal Oct 30 '11 at 09:11

2 Answers2

17

If your root folder is in your pythonpath and you make it an importable package as follows:

/__init__.py
/crawl.py
/crawl/__init__.py
/crawl/john.py
/tests/__init__.py
/tests/test_john.py

you can do:

from crawl.john import John

or

from ..crawl.john import John
joaquin
  • 82,968
  • 29
  • 138
  • 152
  • Seems the root folder is not in my python path. I thought it might add the CWD to the pythonpath but doesn't. Best way to do it? – Wizzard Oct 30 '11 at 09:38
  • that depends on your configuration. In windows, for my packages and libraries I simply add a site.pth file in site-packages with the name of the folder(s). – joaquin Oct 30 '11 at 10:00
2

If your OS supports it, put a symbolic link to ../crawl in the test directory and then use from crawl.john import John.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336