Path Puzzles

Hans Nowak hnowak at cuci.nl
Fri Mar 3 17:43:21 EST 2000


On 3 Mar 00, at 14:41, dogboy777 at my-deja.com wrote:

> I've started using Steve Purcell's wonderful PyUnit test framework, and
> I've run into a problem with paths and modules.  I want to store all of my
> test modules, test files,  in a subdirectory.  What that means is that if,
> for example, I have a module called command.py and an associated testing
> module called tcommand.py, I need to import command. py into tcommand.py.
> tcommand.py needs to know to look for command.py in tcommand.py's parent
> directory.
> 
> So far, I've kludged the problem by setting PYTHONPATH in DOS before I run
> the script from DOS or Linux (we use Samba to map our Win95 clients to our
> Linux server).	This works, but it means that every time I create a new
> project which will have its own test subdirectory, I've got to change
> PYTHONPATH.  There's got to be a better way, right?

This is a way to do this:

#----file 1: addercop.py----------
# addercop.py

def crazycob(x):
    return 2-x

#----end of file 1----------------

#----file 2: lazylob.py
# lazylob.py
# Must be able to import addercop

import sys, os, string

thisdir = os.getcwd()
lastslash = string.rfind(thisdir, "/")
if lastslash == -1:
    raise ImportError, "Cannot import from higher directory"
else:
    higherdir = thisdir[:lastslash]
    print higherdir

sys.path.append(higherdir)

# wheee... it works (well, at least for me ;-)
import addercop
print dir(addercop)

#----end of file 2----------------

Put addercopy.py in the parent directory of lazylob.py and you should be 
able to import it. There must be more elegant methods, but this one seems 
to work... you look what the current directory is, determine the parent 
directory, and add that directory to sys.path. This is not guaranteed to 
work in all circumstances, so be sure to test. 

HTH,

--Hans Nowak (zephyrfalcon at hvision.nl)
Homepage: http://fly.to/zephyrfalcon
You call me a masterless man. You are wrong. I am my own master.




More information about the Python-list mailing list