creating my own module search path

Vassilis Virvilis vasvir at iit.demokritos.gr
Mon Feb 26 00:57:02 EST 2001


Sean 'Shaleh' Perry wrote:
> 
> so, like a good little coder I use functions for code reusability and ease of
> maintenance.  I have a directory structure like:
> 
> ./
>   frontend/
>   lib/
>   ...
> 
> I would like to be able to load files in lib as python modules.  I know how
> to add the directory to sys.path.  The problem is I have a module named
> 'util.py'.  Sure, I could rename it.  But I can not possibly know the name of
> every module on a user's system.  What I was trying to do was add the path
> just before lib to the search path and load it as 'lib.util'.  But this does not
> work.  Suggestions anyone?

Well yeah... What's the difference between lib.util and lib/util? What I
mean is that you can discriminate between modules based on file position
criteria... Please find the relative code snippet attached below. It
works both on linux and win32.

import sys
import os
import imp

def ImportByName(FileName):

        path, basename = os.path.split(FileName)
        name, ext = os.path.splitext(basename)

        # Fast path: see if the module has already been imported.
        try:
                return sys.modules[name]
        except KeyError:
                pass

        # If any of the following calls raises an exception,
        # there's a problem we can't handle -- let the caller handle it.

        fp, pathname, description = imp.find_module(name, [path])

        try:
                return imp.load_module(name, fp, pathname, description)
        finally:
                # Since we may exit via an exception, close fp
explicitly.
                if fp:
                        fp.close()



More information about the Python-list mailing list