1

Desired directory tree:

Fibo
|-- src
|   `-- Fibo.py
`-- test
    `-- main.py

What I want is to call python main.py after cd'ing into test and executing main.py will run all the unit tests for this package.

Currently if I do:

import Fibo

def main():
    Fibo.fib(100)

if __name__ == "__main__":
    main()

I get an error: "ImportError: No module named Fibo".

But if I do:

import sys

def main():
    sys.path.append("/home/tsmith/svn/usefuldsp/trunk/Labs/Fibo/src")
    import Fibo
    Fibo.fib(100)

if __name__ == "__main__":
    main()

This seems to fix my error. And I could move forward... but this isn't a python package. This is more of a "collection of files" approach.

How would you setup your testing to work in this directory structure?

Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177

3 Answers3

1

If I want to import a module that lives at a fixed, relative location to the file I'm evaluating, I often do something like this:

try:
    import Fibo
except ImportError:
    import sys
    from os.path import join, abspath, dirname
    parentpath = abspath(join(dirname(__file__), '..'))
    srcpath = join(parentpath, 'src')
    sys.path.append(srcpath)
    import Fibo

def main():
    Fibo.fib(100)

if __name__ == "__main__":
    main()

If you want to be a good namespace-citizen, you could del the no longer needed symbols at the end of the except block.

Matt Anderson
  • 19,311
  • 11
  • 41
  • 57
  • what about if I want to make Fibo some sort of 'reusable library'? – Trevor Boyd Smith Jun 20 '10 at 17:02
  • If you want to make a module available globally without this sort of adaptive alteration of `sys.path` "just in case", then you need to use the PYTHONPATH environment variable, or install it in a global location that's already being searched. See the documentation for `distutils`. – Matt Anderson Jun 20 '10 at 17:17
0

Adding /home/tsmith/svn/usefuldsp/trunk/Labs/Fibo/src to your PYTHONPATH environment variable would allow you to write

import Fibo

def main():
    Fibo.fib(100)

if __name__ == "__main__":
    main()

and have it import .../Fibo/src/Fibo.py correctly.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

Quick and dirty way: create a symbolic link

razpeitia
  • 1,947
  • 4
  • 16
  • 36