Finding a module's sub modules at runtime

Joshua J. Kugler joshua at eeinternet.com
Tue Apr 3 15:42:14 EDT 2007


On Monday 02 April 2007 16:33, Robert Kern wrote:
>>>>>> help(pkgutil.iter_modules)
>>> Help on function iter_modules in module pkgutil:
>>>
>>> iter_modules(path=None, prefix='')
>>>     Yields (module_loader, name, ispkg) for all submodules on path,
>>>     or, if path is None, all top-level modules on sys.path.
>>>     
>>>     'path' should be either None or a list of paths to look for
>>>     modules in.
>>>     
>>>     'prefix' is a string to output on the front of every module name
>>>     on output.
>> 
>> OK, that looks nice...but what version of Python is that?
>> http://docs.python.org/lib/module-pkgutil.html only shows one function
>> (and that's 2.5) and my python 2.4 installation is similarly lacking an
>> iter_modules() function for the pkgutil module.  Is this a 2.6 thing?
> 
> No, 2.5. The documentation is not up to date. Read the source.
> 

Gotcha.  Thanks...well, since we're using 2.4, that will have to wait.  For
the archives, here is what I've come up with.

Contents of the __init__.py for a module.

import os
_myDir = __path__[0]

def mod_list():
    """
    A quick hack that retrieves all the sub modules in a directory that has
    an  __init__.py file.  I could use pkgutil.iter_modules, but that is
    Python 2.5 only, and this should work with several versions of Python.
    """
    modList = []
    modHash = {}
    isModule = False
    for ii in os.walk(_myDir):
        if ii[0] == _myDir:
            for f in ii[2]:
                # If there is no __init__ file, then the directory
                # upon which mod_list() is operating is not a module
                if f[0:8] == '__init__':
                    isModule = True
                elif f[-3:] == '.py':
                    modHash[f[:-3]] = True
                elif f[-4:] == '.pyc' or f[-4:] == '.pyo':
                    modHash[f[:-4]] = True
    if isModule:
        modList = modHash.keys()
        modList.sort()
        return(modList)
    else:
        return(None)

Hope that helps someone!

j

-- 
Joshua Kugler
Lead System Admin -- Senior Programmer
http://www.eeinternet.com
PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE

-- 
Posted via a free Usenet account from http://www.teranews.com




More information about the Python-list mailing list